java 单利模式
创建单利模式常见的两种方法;
//饿汉式
class Single{
private static final Single s = new Single();
private Single(){};
public static Single getInstance(){
return s;
}
}
//懒汉式
class Single{
private static Single s = null;
private Single(){};
public static Single getInstance(){
if(s == null){
s = new Single();
}
return s;
}
}
//懒汉式 多线程的问题
class Single{
private static Single s = null;
private Single(){};
public static Single getInstance(){
if(s == null){
synchronized(Single.class){//静态方法所以 锁只能用类
if(s == null){
s = new Single();
}
}
}
return s;
}
}
每一步都是一个深刻的脚印