马士兵设计模式笔记1之单例的几种实现方式



//第一种  classic


public class Singleton{

private static Singleton uniqueInstance;
//other useful instance variables here

private Singleton(){}

public  static Singleton getInstance(){
if(uniqueInstance==null){
uniqueInstance=new Singleton();
}

return uniqueInstance;
}

}


//第二种  synchronize


public class Singleton{

private static Singleton uniqueInstance;
//other useful instance variables here

private Singleton(){}

public  static  synchronized Singleton getInstance(){
if(uniqueInstance==null){
uniqueInstance=new Singleton();
}

return uniqueInstance;
}

}




//第三种   eagerly create
public class Singleton{

private static Singleton uniqueInstance=new Singleton();

private Singleton(){}

public  static Singleton getInstance(){


return uniqueInstance;
}

}


//第四种  双检锁
public class Singleton{

private volatile static Singleton uniqueInstance;
private int field1,field2;

private Singleton(){
//initialization
}

public  static Singleton getInstance(){
if(uniqueInstance==null){
synchronized (Singleton.class){
if(uniqueInstance==null){
uniqueInstance=new Singleton();
}
}
}

return uniqueInstance;
}

}




//第五种  lazy initiaization holder class


public class SingletonFactory{

private static class SingletonHolder{
public static Singleton instance=new Singleton();
}

public static Singleton getInstance(){
return SingletonHolder.instance;
}

}


//第六种   Enum Singleton
public enum Elvis{
INSTANCE;
public void leveTheBuiling(){
//.............
}
}



















你可能感兴趣的:(设计模式)