设计模式之单例模式

83 阅读1分钟

单例模式核心:保证一个类只有一个对象

单例模式分为五种:懒汉式、饿汉式、双重检测锁式、静态内部类式、枚举式

五种模式的特点:懒汉式---线程安全,调用效率高,不能延时加载

                           饿汉式---线程安全,调用效率不高,能够延时加载

                           静态内部类式---线程安全,调用效率高,能够延时加载

                           枚举式---线程安全,调用效率高,不能延时加载

                           双重检测锁式有点小问题,用的少,这里就不做说明

占用资源少,不需要延时加载-----枚举 好于 饿汉式

占用资源多,需要延时加载-----静态内部类 好于 懒汉式

饿汉式代码:

public class HungrySingleton{
	private static HungrySingleton instance = new HungrySingleton();
	private HungrySingleton(){}
	public static HungrySingleton getInstance(){
		return instance;
	}
}

懒汉式代码:

public class LazySingleton{
	private static LazySingleton instance;
	private LazySingleton(){}
	public static LazySingleton getInstance(){
	if(instance == null){
			instance = new LazySingleton();
		}
		return instance;	
	}	
}

静态内部类式代码:

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

枚举式代码

public enum Singleton{
	INSTANCE;
	public void MethodName(){
	}
}