java 单例模式的三种写法

public class Singleton {

/**单例模式的实现

* @param args

*/

private Singleton(){

System.out.println("new Singleton begin....");

}

//第一种

/*private static Singleton singleton = new Singleton();

public static Singleton getInstance(){

return singleton;

}*/

//第二种

/*private static Singleton singleton = null;

public synchronized static Singleton getInstance(){

if(singleton == null){

singleton = new Singleton();

}

return singleton;

}*/

//第三种  推荐

private static class SingletonHolder{

private static Singleton singleton = new Singleton();

}

public static Singleton getInstance(){

return SingletonHolder.singleton;

}

public static void main(String[] args) {

/*Singleton s1 = Singleton.getInstance();

Singleton s2 = Singleton.getInstance();

Singleton s3 = Singleton.getInstance();

Singleton s4 = Singleton.getInstance();

Singleton s5 = Singleton.getInstance();

System.out.println(s1);

System.out.println(s2);

System.out.println(s3);

System.out.println(s4);

System.out.println(s5);*/

}

}

猜你喜欢

转载自luckylearn.iteye.com/blog/2383533