单例懒汉式的另一种实现

package cn.interview;

public class SingletonDemo {
	static{
		System.out.println("SingletonDemo load");
	}
	private  SingletonDemo() {
		
	}
	
	
	public static void anyMethod(){
		System.out.println("other method");
	}
	
	static class ClassHolder{
		static{
			System.out.println("ClassHolder load");
		}
		private static SingletonDemo instance = new SingletonDemo(); 
	}
	
	public static SingletonDemo getInstance(){
		return ClassHolder.instance;//调用这句的时候才会静态初始化ClassHolder
	}
	
	
}

测试类:

package cn.interview;

public class SingletonTest {
	public static void main(String[] args) {
		SingletonDemo.anyMethod();
		
		System.out.println("-----------------");
		SingletonDemo demo1 = SingletonDemo.getInstance();
		SingletonDemo demo2 = SingletonDemo.getInstance();
		System.out.println(demo1==demo2);
	}
}

结果:

SingletonDemo load
other method
-----------------
ClassHolder load
true

总结:

成员静态类在里面的方法或者变量被用到的时候才会初始化,

这种单例也可以防止多线程并发问题。

你可能感兴趣的:(单例懒汉式的另一种实现)