Java 23 design patterns singleton pattern

Posted by speckledapple on Mon, 28 Oct 2019 02:00:33 +0100

Original address: https://zhuanlan.zhihu.com/p/...

I. overview

1. What is the singleton mode?

Baidu Encyclopedia is defined as follows: single instance mode is a common software design mode. In its core structure, there is only one special class called singleton. Single instance mode can ensure that there is only one instance of a class in the system.

I understand that the singleton mode only allows one instance. When I first used it, it was in C ා and I wanted to instantiate A form, but there was A requirement that form A must be unique. No matter I operate form A in form B or form C, the singleton mode was used.

2. Single case model classification

A. lazy singleton mode: instantiate itself at the first call. In a concurrent environment, there may be multiple own objects. So threads are not safe

B. starved man singleton mode: during class initialization, a static object has been instantiated by itself, so it is thread safe.

C. registration single instance mode: manage and maintain the single instance of each single instance mode through a special class

3, characteristics

A. a single instance mode class can only have one instance
B. the singleton pattern class must create its own unique instance
C. singleton pattern class must provide this instance to all other objects

Two, use

1. Lazy singleton mode

/**
 * Description: single case mode of lazy person < p >
 * Author: Kimball < p >
 * E-mail: kimballlu@foxmail.com <p>
 * Date: 2016-11-16 4:30:32 PM < p >
 */
public class Singleton {
    
    /**
     * This function restricts the user from actively creating an instance
     */
    private Singleton() {}
    private static Singleton singleton = null;
    
    /**
     * Get Singleton instance (also called static factory method)
     * @return Singleton
     */
    public static Singleton getSingleton() {
        /* When singleton is empty, it is created, otherwise it is returned directly to ensure uniqueness. */
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
    
}

Thread safe lazy singleton mode

Add synchronized synchronization in getSingleton().

/**
 * Description: lazy singleton mode, add synchronization in getSingleton() method < p >
 * Author: Kimball < p >
 * E-mail: kimballlu@foxmail.com <p>
 * Date: 2016-11-16 4:30:32 PM < p >
 */
public class Singleton {
    
/**
     * This function restricts the user from actively creating an instance
     */
    private Singleton() {}
    private static Singleton singleton = null;
    /**
     * Get Singleton instance, also called static factory method
     * @return Singleton
     */
    public static synchronized Singleton getSingleton(){
        if(singleton==null){
            singleton=new Singleton();
        }
        return singleton;
    }
    
}

Double check lock

ps: corrected, still not recommended, thank you
Jiangnan cloth
Comment

For details, please refer to the problem description of correct use of double check lock and failure of double check lock ".

/**
 * Description: lazy single case mode, double check locking < p >
 * Author: Kimball < p >
 * E-mail: kimballlu@foxmail.com <p>
 * Date: 2016-11-16 4:30:32 PM < p >
 */
public class Singleton {

    /**
     * This function restricts the user from actively creating an instance
     */
    private Singleton() {}

    private volatile static Singleton singleton = null;

    /**
     * Get Singleton instance, also called static factory method
     * @return Singleton
     */
    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }

}

Static internal class: static internal analogy double check locking is better than adding synchronization to getInstance() method, which realizes thread safety and avoids performance impact caused by synchronization.

/**
 * Description: lazy singleton mode, static inner class < p >
 * Author: Kimball < p >
 * E-mail: kimballlu@foxmail.com <p>
 * Date: 2016-11-16 4:30:32 PM < p >
 */
public class Singleton {

    /**
     * Static inner class
     * @author kimball
     *
     */
    private static class LazyHolder {
        // Create Singleton instance
        private static final Singleton INSTANCE = new Singleton();
    }

    /**
     * This function restricts the user from actively creating an instance
     */
    private Singleton() {}

    /**
     * Get Singleton instance, also called static factory method
     * @return Singleton
     */
    public static final Singleton getInstance() {
        return LazyHolder.INSTANCE;
    }

}

2. Single case model of starving Han

/**
 * Description: single case model of starving Han
 * Author: Kimball < p >
 * E-mail: kimballlu@foxmail.com <p>
 * Date: 2016-11-16 4:30:32 PM < p >
 */
public class Singleton {

    /**
     * This function restricts the user from actively creating an instance
     */
    private Singleton() {}

    private static final Singleton singleton = new Singleton();

    /**
     * Get Singleton instance, also called static factory method
     * @return Singleton
     */
    public static Singleton getInstance() {
        return singleton;
    }

}

3. Single interest mode of registration

/**
 * Description: registration mode < p >
 * Author: Kimball < p >
 * E-mail: kimballlu@foxmail.com <p>
 * Date: 2016-11-16 4:30:32 PM < p >
 */
public class Singleton {

    // Store instances of classes that need to be maintained and managed
    private static Map<String, Singleton> map = new HashMap<String, Singleton>();
    
    /**
     * Create instances statically and add them to the Map collection
     */
    static {
        Singleton singleton = new Singleton();
        map.put(singleton.getClass().getName(), singleton);
    }

    /**
     * This function restricts the user from actively creating an instance
     */
    private Singleton() {};

    /**
     * Get Singleton instance, also called static factory method
     * @return Singleton
     */
    public static Singleton getInstance(String name) {
        /* Gets an instance from mao based on the name of the specified class and returns */
        return map.get(name);
    }

    // An example business approach
    public String about() {
        return "Hello,I am RegSingleton";
    }

    public static void main(String[] args) {
        Singleton singleton = Singleton.getInstance("com.Singleton");
        System.out.println(singleton.about());
    }

}

Three, conclusion

The above is the single design pattern, although the single design pattern is a relatively simple design pattern of 23 design patterns. But three smelly cobblers can also stand up to one Zhugeliang, which naturally has its own reason for existence.

Design pattern says white dot is a kind of thinking of coding (before in school, the teacher always said thinking thinking, now I also start to say, manual funny)

I look at coding from the perspective of life. Coding is a small version of the world.

Four, supplement

In the above-mentioned implementation of several singleton modes, in one case, they will recreate the object, that is, deserialize, write a singleton instance object to disk and read it back, so as to obtain an instance. The deserialization operation provides the readResolve method, which allows developers to control the deserialization of objects. In the above method examples, if you want to prevent a single object from being deserialized to regenerate the object, you must add the following methods:

private Object readResolve() throws ObjectStreamException{
return singleton;
}

Above excerpts from https://blog.csdn.net/itachi8...
**1. Because enum is implemented by inheriting enum class, enum structure cannot inherit other classes as a subclass, but it can be used to implement interfaces. In addition, enum classes cannot be inherited.
2. enum has and only has private constructors to prevent external extra constructions.**

A singleton mode of enumeration implementation is added.

public enum  SingletonEnum {
    INSTANCE;
}

This completes the implementation. The call is as follows

    @Test
    void singleton(){

        SingletonEnum instance = SingletonEnum.INSTANCE;
    }

For serialization and de serialization, because each enumeration type and enumerated variable are unique in JVM, that is, Java has made special provisions in serialization and anti serialization enumeration. Enumeration of writeObject, readObject, readObjectNoData, writeReplace and readResolve methods are disabled by the compiler, so there is no implementation of serialization interface after calling readObject. The problem of breaking a single case.
Above excerpts from https://www.cnblogs.com/cielo...

If the article is helpful to you, please remember to like it~
Welcome to pay attention to my public account "emotional it", and push technical articles daily for your reference.

Topics: Java jvm