Design Patterns series - Singleton

Singleton pattern in the daily development is more common (in fact, this blog series introduced only in the development of several common design patterns)

Under the concept of simple understanding, singleton: is the use of a certain way, ensure that the entire software system, an object instance of a class exists only. And the class provides only one instance of its static methods to obtain the object

Singleton common are eight ways:

① hungry man type - static constant - will use requirements

② starving formula - Static block - will use requirements

③ lazy style - thread safe - requires an understanding of

④ lazy style - thread safety, synchronization method - requires an understanding of

⑤ lazy style - thread-safe, synchronized block - requested information

⑥ double-checked - will use requirements

⑦ static inner classes - will use requirements

⑧ enumerate - will use requirements

The following eight ways that will explain in detail one by one

The first way: hungry man type - Constant Static

1  // starving formula - static constant 
2  class Singleton {
 . 3      // privatization constructor 
. 4      Private Singleton () {
 . 5      }
 . 6  
. 7      // Create an instance of an object inside the local 
. 8      Private  Final  static Singleton instance = new new Singleton () ;
 . 9  
10      // provide external common static method, it returns an instance of an object 
. 11      public  static Singleton the getInstance () {
 12 is          return instance;
 13 is      }
 14 }

This way is very simple and crude, up is to create a direct instance of an object , and then returns an instance of the object through the static method , pay attention to the constructor must be privatized , otherwise it is not a single external energy new cases of

Explain the advantages and disadvantages

  Advantages: simple wording, when the loading is completed the class is instantiated . Avoid thread synchronization problems

  Disadvantage: When loading is completed the class is instantiated, not reach lazy loading effect. If the job of all it has used this class, will result in a waste of memory

  Conclusion: This single-case model available, may result in wasted memory

The second way: starving formula - static code block

1  // starving formula - Static block 
2  class SingTon_static_final {
 . 3      Private  static SingTon_static_final instance;
 . 4      // privatization constructor 
. 5      Private SingTon_static_final () {}
 . 6      // static block of code - Create singleton object code block in a static 
. 7      static {
 . 8          instance = new new SingTon_static_final ();
 . 9  }
 10      // provide external common static method, returns an instance of an object 
. 11      public  static Singleton the getInstance () {
 12 is          return instance;
 13 is      }
 14 }

In this way even simpler than the static method, when the class is loaded will be generated good examples

Explain the advantages and disadvantages

  Pros: static and constant manner similar. Examples merely examples of the process in a static block of code, when the class is loaded to initialize the class

  Conclusion: This single-case model available, may result in wasted memory

The third way: lazy style - thread safe

 

. 1  class Singleton {
 2      Private  static Singleton instance;
 . 3      // privatization constructor 
. 4      Private Singleton () {
 . 5      }
 . 6      // provides a public static method, created instance of the class to go back to the process used when the time - i.e. formula idler 
. 7      public  static Singleton the getInstance () {
 . 8          IF (instance == null ) {
 . 9              instance = new new Singleton ();
 10          }
 . 11          return instance;
 12 is      }
 13 is }

 

It is clear that this approach is not thread safe

Explain the advantages and disadvantages

  Advantages: played a lazy loading purposes

  Cons: But only in the single-threaded use under. If you use multiple threads, then there will be such a situation, a thread enters the  if (instance == null), but has not yet had time to proceed to the following, this time came in another thread , but also because the previous thread also not so this time the implementation of new SingleTon instance is still null so there will be multiple threads to execute new SingleTon, this will lead to multiple instances . So in this way multithreading is not used, that is, non-thread-safe

  Conclusion: In the actual development, do not use this approach

The fourth way: lazy style - thread-safe - synchronization method

 

. 1  class Singleton {
 2      Private  static Singleton instance;
 . 3      // privatization constructor 
. 4      Private Singleton () {}
 . 5      // provides a public static method, created instance of the class to go back to the process used when the time - - i.e. lazy man 
. 6      public  static  the synchronized Singleton the getInstance () {
 . 7          IF (instance == null ) {
 . 8              instance = new new Singleton ();
 . 9          }
 10          return instance;
 . 11      }
 12 is }

 

As long as this is seen synchronize synchronization method, we know that in this way a certain efficiency is very low, but in fact this is not a thread-safe manner, in short, is not recommended

Explain the advantages and disadvantages

  Pros: to solve the problem of insecurity thread

  Disadvantages: low efficiency . Time because each thread in the acquisition instance of the class when the execution getInstance () method must be synchronized. And in fact, this method is only executed once is enough, want to get back to the example of a direct return method on the line. Inefficient methods to synchronize

  Conclusion: In the actual development, in this way is not recommended

Fifth way: lazy style - thread safety - synchronized block

 

. 1  class Singleton {
 2      Private  static Singleton instance;
 . 3      // privatization constructor 
. 4      Private Singleton () {}
 . 5      // provides a public static method, created instance of the class to go back to the process used when the time - - i.e. lazy man 
. 6      public  static Singleton the getInstance () {
 . 7          IF (instance == null ) {
 . 8               Synchronized (. Singleton class ) {
 . 9                   instance = new new Singleton ();
 10              }
 . 11          }
 12 is          return instance;
13     }
14 }    

 

Not recommended, actually this way is not thread-safe

 

 

Explain the advantages and disadvantages

 

  Cons: This synchronization does not play the role of thread synchronization

 

  Conclusion: not recommended

Sixth ways: double-checking

 1 //双重超检查
 2 class SingleTon {
 3     private static volatile SingleTon instance;
 4     private SingleTon() {}
 5     public static SingleTon getInstance() {
 6         if (instance == null) {
 7             synchronized (SingleTon.class) {
 8                 if (instance == null) {
 9                     instance = new SingleTon();
10                 }
11             }
12         }
13         return instance;
14     }
15 }

Privatization of the constructor, to prevent external new instance, when the thread A, B calls getInstance time, A and B at the same time to reach the first if (instance == null) then advanced to the A, B can only this time on the outside a waiting thread is finished, come in a judge instance is null then a new instance, and the results returned, this time thread B can come in but this time he found instance is not empty, then return directly instance

Explain the advantages and disadvantages

  Pros: perfect solution lazy loading problem, ensure that the thread synchronization, while ensuring the efficiency

  Conclusion: In the actual development, recommended to use this way

Seventh in the way: static inner classes

. 1  class Singleton {
 2      Private Singleton () {
 . 3      }
 . 4      // write a static inner class, which has a static properties: INSTANCT 
. 5      Private  static  class SingleTonInstance {
 . 6          Private  static  Final Singleton INSTANCT = new new Singleton ();
 . 7      }
 . 8      / / provide static announcement method returns directly SingleTonInstance.INSTANCT 
. 9      public  static Singleton the getInstance () {
 10          return SingleTonInstance.INSTANCT;
 . 11      }
 12 is }

This way is the definition of each static inner classes inside the class, this static inner classes which define and create an instance of the class. Then provide external static method returns an instance created in the static inner classes

Explain the advantages and disadvantages

  This method uses a class loading mechanism to ensure initialize instances when only one thread.

  Static inner classes manner in SingleTon when loaded and not immediately instantiated, but calls need to be instantiated when the getInstance () method will load SingleTonInstance class, thus completing the SingleTonInstance instantiation

 

  Static properties of the class will only be initialized when the class is first loaded , so here JVM helps us ensure the security thread ( JVM loading when the class is thread-safe)

Eighth way: Enumeration

 

1  // enum can implement a single embodiment 
2  enum Singleton {
 . 3      // property 
. 4      INSTANCE;
 . 5      public  void SAYOK () {
 . 6          System.out.println ( "the OK" );
 . 7      }

 

Explain the advantages and disadvantages

  Advantages: means JDK1.5 achieved singleton pattern enumerated added. Not only to avoid multi-thread synchronization problems, but also to prevent deserialization re-create a new object

  Conclusion: In the actual development, recommended to use this way

to sum up:

① Singleton pattern to ensure that the memory system there is only one object class, saving system resources, some objects need to frequently create and destroy, using the Singleton pattern can improve system performance

② When a single embodiment want to instantiate class, must remember to use the corresponding method for acquiring an object, instead of using the new

③ singleton pattern of usage scenarios: the need to frequently create and destroy objects, consuming too much or consume too many resources when you create an object (ie: heavyweight objects), but it is frequently used objects, tools Objects , frequent access to the database or object file (such as data source, the session factories, etc.)

 

Guess you like

Origin www.cnblogs.com/zyzblogs/p/11271897.html