单例模式典型创建方法(三种)

单线程

 
class Singleton {
	
	private Singleton() {};
	private static Singleton instance = null;
	
	public static Singleton createInstance() {
		if (instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
	
}
 
public class HelloWorldjava {

	public static void main(String[] args) {
		Singleton s1 = Singleton.createInstance();
		Singleton s2 = Singleton.createInstance();
		
		if (s1 == s2) {
			System.out.println("只有一个实例被创建!");
		}
	}
}
 

预先加载

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


public class HelloWorldjava {

	public static void main(String[] args) {
		Singleton s1 = Singleton.createInstance();
		Singleton s2 = Singleton.createInstance();
		
		if (s1 == s2) {
			System.out.println("只有一个实例被创建!");
		}
	}
}

按需创建

class Singleton {
	
	private Singleton() {};
	
	private static class Helper {
		static Singleton instance = new Singleton(); 
	}
	
	public static Singleton createInstance() {
		return Helper.instance;
	}
	
}

public class HelloWorldjava {

	public static void main(String[] args) {
		Singleton s1 = Singleton.createInstance();
		Singleton s2 = Singleton.createInstance();
		
		if (s1 == s2) {
			System.out.println("只有一个实例被创建!");
		}
	}
}
posted @ 2013-04-26 16:57  helloweworld  阅读(150)  评论(0编辑  收藏  举报