Singleton design mode (hunger and lazy)
1. When to use it: It is recommended that the configuration file be encapsulated into an object when multiple programs read a configuration file. It is convenient to operate on the data, and ensure that multiple programs read the same configuration file object. Therefore, the configuration file object must be unique in the memory.
2. essence: Ensure the uniqueness of an object in the memory of a class.
3. thoughts:
A. Do not allow other programs to create such objects.
B. Create an object in this class.
C. Provide external methods for other programs to obtain this object.
4. Solution steps:
A. the constructor Initialization is required to create objects. As long as the constructor in this class is privatized, other programs cannot create such objects;
B. Create an object of this class in the class;
C. Define a method and return this object so that other programs can obtain this class object through the method. (Role: Controllable)
5. Code implementation:
A, // hungry Chinese
Class Single {
Private Single (){}//Private constructor.
Private staticSingle s = new Single ();//Create a private and static class object.
Public static SinglegetInstance (){//Defines public and static methods and returns this object.
Return s;
}
}
B. Lazy: delayed loading.
Class Single2 {
Private Single2 (){}
Private staticSingle2 s = null;
Public static Single2getInstance (){
If (s = null)
S = new Single2 ();
Return s;
}
}