简洁安全的单例模式——Java

什么都不说了,直接上代码,相信你能懂的

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


测试

public class TestSingleton {

	public static void main(String[] args) {
		Singleton one = Singleton.getInstance();
		Singleton two = Singleton.getInstance();
		System.out.println(one == two);//true
	}

}


简单吧

你可能感兴趣的:(java)