Singleton design pattern and code examples Detailed

First, what is the singleton

  Singleton pattern is defined to ensure that only one instance of a certain class, and provide a global access point. Belonging to the three categories of design patterns 创建型模式. Singleton has three characteristics typical

  • EXAMPLE only a single instance of the object class;
  • The singleton object created by the Self singleton;
  • Singleton class provide external access a single global access point of the embodiment;

  FIG class as follows:

            

  Singleton disadvantages

  • Advantage : due to a single mode, just one embodiment example, it is possible to save system resources, reducing performance overhead, improving system efficiency, but also to strictly control the client access to it.
  • Drawback : it is precisely because there is only one instance, thus leading to a singleton class heavy duty, contrary to the "single responsibility principle", but there is no abstract classes, such expansion has certain difficulties.

Second, how singleton 

  Common Singleton pattern implementations there are 饿汉式five: 懒汉式, 双重检测锁式, , 静态内部类式and 枚举单例. In these five ways 饿汉式and 懒汉式yet the most common.

  1, hungry man style

  Hungry man style of writing thread-safe, high call efficiency. But not delay loading. code show as below:

public class SingletonDemo1 {

    // thread-safe
     // When the class initialization, immediately load the object 
    Private  static SingletonDemo1 instance = new new SingletonDemo1 ();

    private SingletonDemo1() {
    }

    // method does not add a sync block, it high efficiency 
    public  static SingletonDemo1 the getInstance () {
         return instance;
    }
}

  Since this mode when the object loaded class has been created, so the speed class load more slowly, but acquisition targets faster, and is thread safe.

  2, lazy style

  Lazy style of writing thread-safe. Sample code:

public class SingletonDemo2 {

    // thread-safe

    private static SingletonDemo2 instance = null;

    private SingletonDemo2() {
    }

    // load object is run 
    public  static SingletonDemo2 the getInstance () {
         IF (instance == null ) {
            instance = new SingletonDemo2();
        }
        return instance;
    }

}

  Since the object of this mode is loaded at runtime, so the analogy is loaded faster, but get relatively slow speed of the object, and the thread is unsafe. If you want thread-safe, then you can add synchronizedkeywords, but it will pay a heavy expense of efficiency.

  3, double lock detection

public class SingletonDemo3 {

    private static volatile SingletonDemo3 instance = null;

    private SingletonDemo3() {
    }

    //运行时加载对象
    public static SingletonDemo3 getInstance() {
        if (instance == null) {
            synchronized(SingletonDemo3.class){
                 if(instance == null){
                     instance = new SingletonDemo3();
                 }
            }
        }
        return instance;
    }

}

  Double-checked locking, also known as double checking locks, integrated the advantages and disadvantages of both the lazy man and starving style from integration. See the above code implementations, it is characterized by the synchronized keyword inside and outside add a layer if conditional, it will ensure the security thread, locked off than directly improve the efficiency, but also saves memory space.

  Since the singleton=new Singleton()creation of objects may be reordered in the JVM, there is a risk in a multithreaded access, use, volatilemodification signletoninstance variables effectively solve the problem.

  4, static inner classes

public class Singleton { 
    private Singleton(){
    }
      public static Singleton getInstance(){  
        return Inner.instance;  
    }  
    private static class Inner {  
        private static final Singleton instance = new Singleton();  
    }  
} 

  Manner similar to the effect of static inner class double lock object, but the implementation is simpler. However, this approach is only applicable to the case of a still domain, a double lock detection mode can be used when a delay required to initialize instance fields.

  Only the first call getInstance method, the virtual machine to load and initialize Inner instance, only one thread can obtain the lock object initialization, other threads can not be initialized, ensure the uniqueness of the object. At present, this is the way all singleton most recommended mode, but still based on the specific project selection.

  5, enumeration singleton

public enum Singleton  {
    INSTANCE 
 
    // doSomething the instance of behavior support
      
    // can be omitted, this method operates by Singleton.INSTANCE 
    public  static the Singleton the getInstance () {
         return Singleton.INSTANCE;
    }
}

  Create a default enumerate instances are thread-safe, and are single cases under any circumstances. Actually

  • Enum class hides private constructor.
  • Enumeration class is an instance of the object field corresponding type.

  It is well known Singleton pattern is to create a schema, will create a new instance. So an important question is deserialized. When the instance is written to the file when deserialized into instances, we need to override readResolvethe method to make instances unique.

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

Third, the expansion of the singleton

  Singleton pattern can be extended to more limited embodiment (Multitcm) model, which can be generated and stored in a limited number of instances ArmyList, a random access for a customer needs, the structure as shown in FIG:

              

  In everyday situations there are, for example, has five bank counter window, no matter which window you can randomly go to conduct business, but it only has five sales, codes are as follows:

public class BusinessWindow {

    private  static  int maxBusinessWindow = 5 ;

    private static ArrayList<String> NoList = new ArrayList<String>();

    private static ArrayList<BusinessWindow> businessWindowList = new ArrayList<BusinessWindow>();

    private static int currentBusinessWindow = 0;

    static{
        for(int i=0; i<maxBusinessWindow; i++){
            businessWindowList.add ( new new businessWindowList (I + "window number" ));
        }
    }

    private BusinessWindow(){}

    private BusinessWindow(String name){
        NoList.add(name);
    }

    public static BusinessWindow getInstance(){
        Random random = new Randow();
        currentBusinessWindow = randow.nexInt(maxBusinessWindow);
        return businessWindowList.get(currentBusinessWindow);
    }

    public static void doSomething(){}
}

Fourth, the common scenarios

  • Website counter.
  • Project for the class to read configuration files.
  • Database connection pool. Because the database is a database connection pool resources.
  • Spring, each Beandefault is a single embodiment, it is easy to manage Spring container.
  • Servlet inApplication
  • Windows Task Manager, the Recycle Bin.
    and many more.

Guess you like

Origin www.cnblogs.com/jing99/p/12590686.html