单例模式的三种写法



这里介绍三种单例模式写法。

第一种:饿汉模式
类加载时就初始化

public class SingleTonHungry {
	private static SingleTonHungry singleTonHungry = new SingleTonHungry();
	private SingleTonHungry(){
		
	}
	public static SingleTonHungry getInstance(){
		return singleTonHungry; 
	}
}

第二种:懒汉模式

类加载时不初始化,当调用getInstance方法时初始化

public class SingleTonIdler {
	private static SingleTonIdler singleTonIdler;
	private  SingleTonIdler() {
	}
	public static SingleTonIdler getInstance(){
		if(singleTonIdler == null){
			singleTonIdler = new SingleTonIdler();
		}
		return singleTonIdler;
	}
}

第三种:使用静态内部类

public class SingleTonStaticClass {
	private SingleTonStaticClass(){
	}
	
	public static final SingleTonStaticClass getInstance(){
		return SingleTon.singleTonStaticClass;
	}
	
	private static class SingleTon{
		private static final SingleTonStaticClass singleTonStaticClass = new SingleTonStaticClass();
	}
}



你可能感兴趣的:(JAVA,单例模式)