Java design patterns - creational pattern - singleton

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

PS: The first attempt to send blog, if deficiencies are welcome to a lot of guidance!

Singleton pattern (the Singleton)

  • The central role
  • Ensure that only one instance of a class, and provides access to the instance of a global access point

Common scenarios

  • Project, the class reads the configuration file, usually only one object, it is not necessary to use profile data each time, every time a new object is to read
  • Database connection pool designs are generally single-mode embodiment, because the database is a database resource connection
  • spring, each is a single default bean embodiment, the advantage that the container can be managed spring
  • In the spring MVC frame / struts1 frame, the object is also a single embodiment of the controller
  • A typical application is an example of a single application
  • In the servlet program, each embodiment is also a single servlet

Singleton pattern advantage

  • Since the single pattern generating only one example embodiment, the system reduces performance overhead when generating an object requires more resources, such as reading configuration, dependency produce other objects, may be produced by a single direct application startup embodiment object and permanent way to solve the memory-resident
  • Singleton pattern may be provided in the system global access point, optimization loop shared resource access, for example a singleton class design, responsible for mapping the processing of all data tables

Five common ways to achieve Singleton pattern

  • Main
    - starving formula (thread-safe, high-efficiency calls, but can not delay load)
    - lazy man's (thread-safe, call the efficiency is not high, but can be delayed load)
    - Other
    - dual detection lock (due to the underlying JVM internal models The reason, occasional problems, not recommended)
    - static inner class type (thread-safe, high-efficiency calls, can delay load)
    - enumeration singleton (thread-safe, high-efficiency calls, the delay can not be loaded)

How to choose?

  • Singleton objects occupy less resources without delay to load
    the enumeration type is better than starving formula
  • Singleton object large footprint, we need to delay loading
    static inner class style better than the lazy man

Starving formula (singleton object immediate loading)

  • Hungry man single-case model code, static variables are initialized when the class is loaded, this time it will not involve multiple threads object access problems of the object, the virtual machine to ensure that only loads once the class, certainly will not happen concurrent access the problem, therefore, can be omitted synchronized keyword
    - if only to load this class, rather than to be called getSingleton (), never even called, will result in waste of resources

      class SingletonEHan{
          //类初始化时,立即加载这个对象(没有延时加载的优势,)加载时,天然的是线程安全的
          private static SingletonEHan singleton = new SingletonEHan();
      
      
          //私有化构造器
          private SingletonEHan() {
          }
      
          //方法不同步,调用效率高
          public static SingletonEHan getSingleton() {
              return singleton;
          }
    
      }
    

Lazy formula (delay singleton object loading)

  • lazy load delay loading, lazy loading, when it is loaded with real
    - high resource utilization, but each call getSingleton () method must be synchronized, concurrent low efficiency

      class SingletonLHan{
          //类初始化时,不初始化这个对象,延时加载,真正需要时再创建
          private static SingletonLHan singleton;
      
          //私有构造器
          private SingletonLHan() {
          }
      
          //方法同步,调用效率低
          public static synchronized SingletonLHan getSingleton() {
              if (singleton == null){
                  singleton = new SingletonLHan();
              }
              return singleton;
          }
      }
    

Dual detection mode lock

  • This model will be below the synchronous content to internal if, improve the efficiency of execution, have no need to be synchronized, only the first sync only created after the time do not always get the object
    - Since the compiler to optimize the underlying causes and internal JVM model reason, occasionally go wrong, is not recommended

      class SingletonDouble{
          private static SingletonDouble singleton;
      
          //私有构造器
          private SingletonDouble(){}
      
          //
          public static SingletonDouble getSingleton(){
              if (singleton == null){
                  SingletonDouble sc;
                  synchronized (SingletonDouble.class){
                      sc = singleton;
                      if (sc == null){
                          synchronized (SingletonDouble.class){
                              if (sc == null){
                                  sc = new SingletonDouble();
                              }
                          }
                          singleton = sc;
                      }
                  }
              }
              return singleton;
          }
      }
    

Static inner classes (also a lazy load)

  • External class does not have static property, then load the object will not be as immediate as a hungry man style

  • Only true calling getSingleton (), will load the static inner classes, when loading the class is thread-safe, singleton static final type is to ensure that the memory of such an instance exists only, and can only be assigned once, thus ensuring the security thread sex.

  • It combines the advantages of efficient concurrent calls and delayed loading

      class SingletonStatic{
          //创建一个静态内部类
          private static class SingletonClass{
              private static final SingletonStatic singleton = new SingletonStatic();
          }
      
      	//调用时,通过return 再创建
          public static SingletonStatic getSingleton(){
              return SingletonClass.singleton;
          }
      
          //私有构造器
          private SingletonStatic(){}
      }
    

Enumeration singleton

  • Advantages: simple, enumeration itself it is a singleton, provide protection fundamentally by the JVM, to avoid loopholes through reflection and deserialized

  • Cons: No Delay Load

      enum  SingletonEnum{
          /**
           * 定义一个枚举的元素,它就代表了Singleton的一个实例
           */
          INSTANCE;
          /**
           * 单例可以有自己的操作
           */
          public void singletonOperation(){
              //功能处理
          }
      }
    

Guess you like

Origin blog.csdn.net/weixin_44395637/article/details/92402932