The basic concept of a single case pattern for design patterns
Singleton mode is a kind of design pattern of production object type.
A singleton pattern refers to an object of a class that only allows 1 instances (objects) at the same time.
Realize
Suppose there is a class King:
public class King {}
Ordinary classes can create objects arbitrarily:
King k1 = new King();King k2 = new King();King k3 = new King();
Because when you create a class and do not explicitly specify a constructor method, it is equivalent to:
public class King { public King() { }}
To implement Singleton mode, first of all, you must not allow arbitrary creation of objects! The
public class King { private King() { }}
Once the construction method is privatized, it is not allowed to call the constructor method outside of the class! At this point, only the inside of the class can invoke the constructor method to create the object:
public class King { private King king = new King(); private King() { }}
In the above code, the King object created is the only object created! Then, when the external needs of the class, provide a matching get method!
public class King { private King k = new King(); private King() { } public King getInstance() { return k; }}
Although the above code may seem feasible, the getinstance () method cannot be invoked when actually used. To ensure that the getinstance () method can be called before an object without a King class, it must be decorated with static:
public class King { private King k = new King(); private King() { } public static King getInstance() { return k; }}
Because of a member that is modified by static, you can only access other static members (not other non-static members), because once the static is used, the member will be loaded into memory with the highest priority! Other data that has not been modified by static is not loaded into memory at this time, so it cannot be accessed! Finally, you also need to use static to modify the object of King:
public class King { private static King k = new King(); private King() { } public static King getInstance() { return k; }}
A singleton pattern in Java