单例模式原理:
单例模式又叫做 Singleton模式,指的是一个类,在一个JVM里,只有一个实例存在。
关键要实现三点:
1. 构造方法私有化,使得外部无法通过new 得到新的实例
2. 静态属性指向实例,使整个类只有一个实例属性值
3. public static的 getInstance方法,返回第二步的静态属性,外部只能从该方法获得实例
实现方法:
public class SingletonTest2 {
//构造函数私有
private SingletonTest2() {
}
//定义私有静态属性,指向生成的唯一实例
private static SingletonTest2 instance;
//外部可访问的方法,返回私有静态属性
public static SingletonTest2 getInstance() {
if (null == instance) {
instance = new SingletonTest2();
}
return instance;
}
}