java design pattern - singleton (singleton)

Singleton pattern is a commonly used software design pattern. In its core structure it contains only a special class called a singleton. The singleton pattern can ensure that in the system, a class that applies this pattern has only one instance of a class. That is, a class has only one object instance

How to ensure object uniqueness?

Thought:

1. Do not allow other programs to create objects of this class.

2. Create an object of this class in this class.

3. Provide external methods to allow other programs to obtain this object.

step:

1. Because creating an object requires constructor initialization, as long as the constructor in this class is privatized, other programs can no longer create objects of this class;

2. Create an object of this class in the class;

3. Define a method to return the object, so that other programs can get the object of this class through the method. (function: controllable)

Code reflects:

1. Private constructor;

2. Create a private and static object of this class;

3. Define a public and static method that returns the object.

There are two ways to implement the singleton mode: one is the hungry style, which is instantiated in advance before the object needs to be used, and the other is the lazy style, which does not create an instance first, and then instantiates it when other objects are called.

// Hungry 
class Single{
   private Single(){} // Private constructor. 
   private  static Single s = new Single(); // Create a private and static object of this class. 
   public  static Single getInstance(){ // Define a public and static method that returns the object. 
    return s;
    }
  }
// Lazy: lazy loading method. 
    class Single2 {
         private Single2() {}
         private  static Single2 s = null ;
         public  static Single2 getInstance() {
             if (s == null )
                s = new Single2();
            return s;
        }
    }

 

Guess you like

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