标签:style blog color os div log sp new on
声明一个Singleton类的3种方法:
package com.twoslow.cha2; /** * 可以通过AccessibleObject.setAccessible(),通过反射机制调用私有构造器。 * @author sai * */ public class Singleton01 { private Singleton01(){} public static final Singleton01 INSTANCE = new Singleton01() ; private Object readResolve() { return INSTANCE ; } }
package com.twoslow.cha2; /** * 可以通过AccessibleObject.setAccessible(),通过反射机制调用私有构造器。 * @author sai * */ public class Singleton02 { private Singleton02(){} private static final Singleton02 INSTANCE = new Singleton02() ; public static Singleton02 getInstance() { return INSTANCE ; } private Object readResolve() { return INSTANCE ; } }
package com.twoslow.cha2; /** * 为了实现单例类可序列化,仅仅在声明中添加implements Serializable是不够的。 * 必须声明所有实例域是瞬时(transient)的,并提供一个readResolve方法。否则, * 每次反序列化一个序列化的实例时,都会创建一个新的实例。 * 单元素的枚举类型提供了序列化机制,是实现Singleton最佳方法。 * @author sai * */ public enum Singleton03 { INSTANCE ; }
第二章:创建和销毁对象。ITEM3:用私有构造器或者枚举类型强化Singleton属性。
标签:style blog color os div log sp new on
原文地址:http://www.cnblogs.com/twoslow/p/3936247.html