1. Concept
Ensure that a class has only one instance (construction method privatization) and provides a global access point (static GetInstance method) to access it.
2. Realization of Ideas
To control that a class is created only by an instance, the first problem is to take the permissions of the created instance back and let the class itself take care of the creation of its own class instance, and then this class provides a way for the external access to the class instance.
3. How to implement
1) Lazy Type
2) A Hungry man type
Lazy: Always create an object instance when the Dodge is not open.
A hungry man: Since you are hungry, you are more anxious when creating an object instance, so you create an object instance when the class is loaded.
4. Example (lazy type)
public class singleton{
//私有话的构造函数 private Singleton(){ } //静态的存储变量 private static Singleton mInstace; //获得实例的入口 public static Singleton getInstance(){ if(mInstance == null){ mInstance = new Singleton(); } return mInstance; }
}
Design mode: 5) Singleton mode