设计模式之单例模式
单例模式:
保证只有一个实例存在
避免产生多个对象消耗资源,或者某种对象只应该有且仅有一个
注意: 1.构造函数不对外开发,一般private
2.通过静态方法或枚举返回单例类对象
3.确保单例对象有且仅有一个,尤其在多线程环境下
4.确保单例对象在反序列化时不会重新构建对象
//饿汉式 public class SingleTon { private SingleTon(){} private static final SingleTon single = new SingleTon(); public static SingleTon getSingle(){ return single; } }
//懒汉模式 public class SingleTon{ private SingleTon(){} private static SingleTon single = null; public static synchronized SingleTon getSingle(){ if(single ==null){ single = new SingleTon(); } return single; } }
//Double check Lock(DCL) public class SingleTon{ private SingleTon(){} private static SingleTon single = null; public static SingleTon getSingle(){ if(single == null) synchronized(SingleTon.class){ if(single ==null){ single = new SingleTon(); } } return single; } }
//静态内部类 public class SingleTon{ private SingleTon(){} public static SingleTon getSingle(){ return SingletoHolder.single; } private static class SingletoHolder{ private static final SingleTon single = new SingleTon(); } private Object readResolve() { return SingletoHolder.single; } }
//枚举单例 public enum Single { INSTACE; }
一般情况下DCL 使用最多但是反序列化还是可以重新生成对象
private Object readResolve() throws ObjectStreamException{ return single; }
还有一种用容器实现:
public class SingletoManager { private SingletoManager(){ } private static Map<String,Object> map = new HashMap<String,Object>(); public static void registerService(String key,Object instance){ if(!map.containsKey(key)){ map.put(key, instance); } } public static Object getService(String key){ return map.get(key); } }