Singleton design pattern: (solve that a class only has one object in memory)

Singleton design pattern: (solve that a class only has one object in memory)

Question: How to make a class have only one object in memory?

Thought:

  1. It is forbidden for other programs to create such objects;
  2. Since such objects cannot be created externally, they are created in this class;
  3. In order for other programs to access the objects created in this class, an access method should be provided to the outside world

 

How to use code to reflect (java): (can also be implemented in C++, other languages, etc.)
  1. Private constructor;
  2. Create an object in this class;
  3. Provide a way to access objects of this class to the outside world

Code:

class Object{
    String name;    
    static Object o= new Object();  //2. Create an object in this class;
     public  static Object getObject(){    //3. Provide the outside world with a method to access the object of this class
         return o;
    }
    private Object(){};  //1. Private constructor;
}

public class oneObject{
    public static void main(String [] arge){
        Object a = Object.getObject();  //The first object 
        a.name = "Joke" ;           //Modify the attribute name in the first object, and also modify the name attribute 
        Object b in the second object = Object.getObject();  //Second object
        System.out.println(b.name);
    }
}

Results of the:

 

Guess you like

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