Definition:

Ensure a class has only one instance, and provide a global point of access to it.

Common code (thread-safe)

public class Singleton {
     private static final Singleton singleton = new Singleton();
     // Restrict the generation of multiple objects
     private Singleton(a){}// Use this method to get the instance object
     public static Singleton getSingleton(a){
     return singleton;
     } 
     // All other methods in the class should be static
     public static void doSomething(a){}}Copy the code

Usage scenarios

  1. An environment that requires the generation of a unique sequence number
  2. A shared access point or shared data is needed throughout the project, such as a counter on a Web page, which can be saved from logging every refresh to the database, using a singleton pattern to keep the value of the counter and ensure that it is thread-safe;
  3. Creating an object consumes too many resources, such as accessing IO and database resources
  4. Environments where you need to define a large number of static constants and static methods (such as utility classes) can use the singleton pattern (or, of course, declare it static).

Thread unsafe form

/** * You can use the synchronized keyword on getSingleton() or add the synchronized keyword to the getSingleton() method block to make it thread-safe
public class Singleton {
     private static Singleton singleton = null;
     // Restrict the generation of multiple objects
     private Singleton(a){}// Use this method to get the instance object
     public static Singleton getSingleton(a){
         if(singleton == null){
             singleton = new Singleton();
         }
         returnsingleton; }}Copy the code