一、构成单例模式要点:
①、只有一个实例
②、私有的构造方法
③、向外界提供访问该实例的公共的静态方法
二、分类:
①、饿汉模式
class SingletonOne {
private SingletonOne() {
}
private static SingletonOne st = new SingletonOne();
public static SingletonOne getST() {
return st;
}
}
②、懒汉模式1
class SingletonTwo {
private SingletonTwo() {
}
private static SingletonTwo st = null;
public synchronized static SingletonTwo getST() {
if (st == null)
st = new SingletonTwo();
return st;
}
}
③、懒汉模式2
class SingletonThr {
static class creatSingleton {
static SingletonThr st = new SingletonThr();
}
public static SingletonThr getST() {
return SingletonThr.creatSingleton.st;
}
}