Design Patterns (4) - Singleton Pattern

singleton pattern

    1. Definition

     Guarantees that there is only one instance of a class, and provides a global access point to it.

         2. Sample code

    

/* Hungry Chinese-style singleton mode, objects are created when the class is loaded, thread-safe */
public class Singleton{
   //Create an instance when the class is loaded, and static guarantees that it will be created once
   public static Singleton instance = new Singleton();
   //private constructor
   private Singleton(){
   }
   //Define a static method to provide the instance
   public static Singleton getInstance(){
      //Return directly to the created instance
      return instance;
   }
}

   

/*Lazy singleton mode, create an instance when using it, thread-unsafe*/
public class Singleton{
   private static Singleton instance = null;
   //private constructor
   private Singleton(){
   }
   //Provide a method for obtaining an instance, which is thread-safe only with synchronization
   public static Singleton getInstance(){
        / / Determine whether the instance is generated, if not, create it
        if(instance = null){
             instance = new Singleton();
        }
        return instance;
   }
}

 

   3. Practical application

   
     In addition to the above two ways to implement the singleton pattern, there are also implementation methods through static inner classes and enumeration classes.

 

The essence of the singleton pattern: controlling the number of instances

 

 

    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326357034&siteId=291194637