About Singleton singleton
Singleton singleton class by:
- Use a class variable to cache instances have created
- Hide constructor
- GetInstance define ways to achieve this kind can only create an object.
public class Singleton {
//使用一个类变量来缓存曾经创建的实例
private static Singleton instance;
//隐藏构造器
private Singleton(){}
//提供一个静态方法,用于返回Singleton实例
//该方法可以加入自定义控制,保证只产生一个实例
public static Singleton getInstance(){
//如果instance为null,则表明还没有创建实例
//如果instance不为null,则表明已经存在了实例,将不会再创建对象
if (instance == null){
//创建一个Singleton对象
instance = new Singleton();
}
return instance;
}
}