单例

恶汉模式
public class hungrysingleton implements Serializable{
private final static hungrysingleton h;
static {
h=new hungrysingleton();
}
private hungrysingleton(){
if(h!=null){
throw new RuntimeException("单利模式禁止反射");
}

}
public static hungrysingleton getinstance(){
return h;
}
private Object readResolve(){
return h;
}

}

懒汉模式
public class Lazysingle {
private static Lazysingle lazysingle=null;

private Lazysingle() {
}

public static Lazysingle getInstance(){
if(lazysingle==null){
synchronized (Lazysingle.class){
if(lazysingle==null){
lazysingle=new Lazysingle();
}
}

}
return lazysingle;
}
}

public class Lazysingle2 {
private volatile static Lazysingle2 lazysingle=null;

private Lazysingle2() {
}

public static Lazysingle2 getInstance(){
if(lazysingle==null){
synchronized (Lazysingle2.class){
if(lazysingle==null){
lazysingle=new Lazysingle2();
}
}

}
return lazysingle;
}
}
posted @ 2019-06-20 23:42  黑魔法os  阅读(123)  评论(0编辑  收藏  举报