Singleton pattern analysis of java design pattern

  • 2020-10-07 18:41:51
  • OfStack

Singleton is one of the simplest but also important design patterns with the following advantages:

1. Singleton mode can save memory and improve performance when classes with very large memory footprint need to be created and destroyed frequently, such as sessionFactory in myBatis

2. When single 1 reading and writing to a file is needed, for example, only one windows text file can be written at the same time, singletons are needed to avoid multiple reads and writes

The disadvantage is that:

1. The singleton has no interface, so it is difficult to expand it.

2. Not conducive to testing, it is impossible to directly test one object according to the interface mock

Finally, there are two main ways to realize it: the hungry man model and the lazy man model. Among them lazybones pattern can be subdivided into several kinds, say again later.

Hungry Man mode code:


 public Class Singleton{
 // Instantiate itself when the class loads, the Hunk pattern 
  private static Class Singletom instance = new Singleton();
  private Singleton(){};
  
  public getInstance(){
   return this.instance 
  }
 } 

Slacker mode and thread safe code 1


public Class Singleton{
  private static Class Singletom instance = null;
  private Singleton(){};
  
  public static Singleton getInstance(){
   if(instance==null){
   // Double - detect lock slacker mode if it is directly in getInsance Lock it because there is 99% The situation is thread-safe, will increase the performance consumption, hence the dual detection lock, optimize the lock, make the lock only in 1% Of the situation before implementation  
   synchronized (Singleton.class) {

if (singleton == null) 
{ 
    singleton = new Singleton(); 
    } 
    } 
   return this.instance 
  } 
}

Slacker mode and thread - safe code 2


public Class Singleton{
  // The way static inner classes should be because classLoader The inner class will not be in the class   
  // It is instantiated at load time, so it works 
  private static Class SingletomLoader(){
   private static Singleton instance = new Singleton();
  }
  private Singleton(){};
  
  public static final Singleton getInstance(){
   
   return SingletomLoader.instance 
  }
 }  

Summary: bean in THE spring container USES singleton mode. The spring container controls the life cycle of its bean, while the J2EE container is responsible for the life cycle of its objects if it is set to multi-instance mode.


Related articles: