[Design Mode] singleton

A Profile

  Singleton pattern is a common software design pattern, which is defined as the class of a single embodiment allows only one instance of the object exists.

  Many times the entire system only need to have a global object, this will help us coordinate the overall behavior of the system.

  For example, in a server program, the server configuration information is stored in a file, the configuration data is read by a singleton object unity, then the other objects in the process of re-acquiring service configuration information through the singleton object. This approach simplifies the configuration management in complex environments.

Two  basic realization of ideas

  For single embodiment mainly through the following two steps:

    1, the class constructor is defined private method sole instance, at the other so that the code can not be instantiated class object by calling the constructor of the class, the class obtained by only static methods provided by the class of ;

    2, provides a static method in the class, when we call this method, if the class is not empty hold a reference to this reference is returned, if a class reference to create instances of the class is empty and will remain reference to an instance of This class gives references maintained.

Three Precautions

  Singleton must be careful in the use of multi-threaded applications. If and when the only instance has not been created, there are two threads simultaneously create a method call, then they also did not detect the presence of a unique instance, so while each creates an instance, there are two such instances are constructed, thus violating the single the only principle mode of embodiment examples. The solution to this problem is to provide a mutex (although this will reduce the efficiency) to indicate whether the class has been instantiated variables.

Several of writing four singleton

1 starving mode (static variables) [available]

/**
 * Singleton - starving mode
 */
public class Singleton {
    private static Singleton singleton = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return singleton;
    }
}

  Advantages: such an approach is relatively simple, that is, when the loading is completed the class is instantiated. Since the class loader is thread-safe, thus avoiding thread synchronization issues.

  Disadvantage: when the class is instantiated loading is completed, the loading does not reach the delay effect. If you have never used this example from start to finish, this instance of the object will remain in memory, will result in a waste of memory.

Mode 2 starving - variant (static code block) [available]

class Singleton1 {
    private static Singleton1 singleton;

    static {
        singleton = new Singleton1();
    }

    private Singleton1(){}

    public static Singleton1 getInstance(){
        return singleton;
    }
}

  In this manner the above manner and it is actually quite similar, except that the process of the class is instantiated on static code block, when the class is loaded, to execute the code block static code, instance initialization class. Advantages and disadvantages and the above is the same.

3 double checking locks [recommended]

class Singleton2 {
    private static volatile Singleton2 singleton;

    private Singleton2(){}

    public static Singleton2 getInstance(){
        if (singleton == null){
            synchronized (Singleton2.class){
                if (singleton == null){
                    singleton = new Singleton2();
                }
            }
        }
        return singleton;
    }
}

  Double-Check concept for multi-threaded developers will not be unfamiliar, as shown in the code, we conducted two if (singleton == null) examination, so as to ensure the security thread. Thus, with examples of code is executed only once, when accessed again later, it is judged if (singleton == null), the direct return object instance.

  Meanwhile, in order to prevent the reordering of instructions, when executed new Singleton method, Singleton volatile objects need modification .

  Pros: thread-safe; lazy loading; high efficiency.

  Cons: still can not be avoided by calling the constructor to initialize reflection of the way .

4 static inner classes [recommended]

class Singleton3 {
    private Singleton3(){}
    public static final Singleton3 getInstance(){
        return SingletonHoder.Instance;
    }
    private static  class SingletonHoder{
        private static final Singleton3 Instance = new Singleton3();
    }
}

  In this way a hungry man type way with the mechanism adopted similar, but different. Both such mechanisms are employed to ensure that loading only one thread instance initialization. In different places as long as the method is starving formula Singleton instantiates the class is loaded, no effect Lazy-Loading A static mode when inner class Singleton class is loaded and instantiated not immediately, but need to instantiate when calling getInstance method will loaded carrier SingletonHoder class to complete the instantiation of Singleton.

  Static properties of the class is first loaded only when the class is initialized, so here, JVM helps us ensure the security thread, when the class is initialized, the other thread is inaccessible.

  Advantages: Avoid thread insecure, lazy loading, high efficiency.

5 enumeration [recommended]

public enum Singleton {  
    INSTANCE;  
    public  void getOtherMethod () {  
    }  
}

Calls is very simple:

Singleton.INSTANCE.getOtherMethod();

  Mode is achieved by means of a single enumeration embodiment JDK1.5 added. Not only to avoid multi-thread synchronization problems, but also to prevent deserialization re-create a new object.

  Advantages: system memory, there is only one object class, saving system resources, to create some objects that require frequent destruction, single-use-case model can improve system performance.

  Cons: Whenever you are trying to instantiate a singleton class, we must remember to use the appropriate method to get the object, instead of using new, causing distress may give other developers, in particular, can not see the source code of the time.

  Applications:

  1. We need to create and destroy objects frequent;
  2. When you create an object consuming too much or spend too many resources, but frequently used objects;
  3. Tools objects;
  4. Object databases or frequently accessed files.

Guess you like

Origin www.cnblogs.com/aiqiqi/p/11671225.html