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;
}

}

posted @ 2018-07-04 21:10  仙人掌的成长  阅读(134)  评论(0编辑  收藏  举报