单例模式的另外三种方法
单例模式的另外三种方法
静态内部类:
public class MyObject { private static class MyObjectHandler{ private static MyObject myObject = new MyObject(); } private MyObject() { } public static MyObject getInstance() { return MyObjectHandler.myObject; } }
静态内部类反序列化问题:
import java.io.ObjectStreamException; import java.io.Serializable; import com.stono.thread2.ThreadPrint; public class MyObject implements Serializable { private static final long serialVersionUID = -3968427143706472470L; private static class MyObjectHandler{ private static final MyObject myObject = new MyObject(); } private MyObject() { } public static MyObject getInstance() { return MyObjectHandler.myObject; } protected Object readResolve() throws ObjectStreamException{ ThreadPrint.print("调用了readResolve方法"); return MyObjectHandler.myObject; } }
static代码块:
public class MyObject { private static MyObject myObject = null; private MyObject() { } static { myObject = new MyObject(); } public static MyObject getInstance() { return myObject; } }
enum枚举类型:
import java.util.Date; import com.stono.thread2.ThreadPrint; public enum MyObject { connectionFactory; private Date connection; private MyObject() { try { ThreadPrint.print("调用了MyObject的构造函数"); connection = new Date(); } catch (Exception e) { e.printStackTrace(); } } public Date getConnection() { return connection; } }
单一职责:
import java.util.Date; import com.stono.thread2.ThreadPrint; public class MyObject { public enum MyEnumSingleton{ connectionFactory; private Date connection; private MyEnumSingleton() { try { ThreadPrint.print("调用了MyObject的构造函数"); connection = new Date(); } catch (Exception e) { e.printStackTrace(); } } public Date getConnection() { return connection; } } public static Date getConnection() { return MyEnumSingleton.connectionFactory.getConnection(); } }