This article was compiled by Colodoo (Paper Umbrella) from the reference book graphic Design Patterns

QQ 425343603 Java Learning Exchange Group (717726984)

The singleton pattern

A pattern that ensures that only one instance is generated is called a Singleton pattern.

role

Contains the role

  • Singleton

Singleton

In Singleton mode, there is only one role, Singleton. There is a static method in the Singleton role that returns a unique instance. This method always returns the same instance.

The class diagram

Code sample

package com.zhisan.singleton;

/** * singleton mode **@authorColodoo (paper umbrella) **/
public class Singleton {
    
    // Create a singleton
    private static Singleton = new Singleton();
    
    // Constructor (set private)
    private Singleton(a) {}
    
    // Get the singleton
    public static Singleton getInstance(a) {
        returnsingleton; }}Copy the code
package com.zhisan.singleton;

/** * Run class **@authorColodoo (paper umbrella) **/
public class Main {
    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance();
        Singleton singleton1 = Singleton.getInstance();
        
        if (singleton == singleton1) {
            System.out.println("Same instance!");
        } else {
            System.out.println("Different instances!"); }}}Copy the code