标签:
单例模式,是指一个类只有一个唯一的实例,一个类只会被实例化一次。实现这种效果,最佳的方式,编写包含单个元素的枚举类型。
单例模式的最佳实现方式-----创建一个包含单个元素的枚举类
public enum Elvis { ONE_INSTANCE; public void leaveTheBuilding() { System. out.println("Whoa baby, I‘m outta here!" ); } } ---------------------------------- public class Test { public static void main(String[] args) { Elvis elvis = Elvis. ONE_INSTANCE; elvis.leaveTheBuilding(); } }
public class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() { } public void leaveTheBuilding() { System. out.println("Whoa baby, I‘m outta here!" ); } // This code would normally appear outside the class! public static void main(String[] args) { Elvis elvis = Elvis. INSTANCE; elvis.leaveTheBuilding(); } }
public class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() { } public static Elvis getInstance() { return INSTANCE ; } public void leaveTheBuilding() { System. out.println("Whoa baby, I‘m outta here!" ); } // This code would normally appear outside the class! public static void main(String[] args) { Elvis elvis = Elvis. getInstance(); elvis.leaveTheBuilding(); } }
public class Elvis implements Serializable { /** * */ private static final long serialVersionUID = 1L; public static final Elvis INSTANCE = new Elvis(); private String one; private Elvis() { } public void leaveTheBuilding() { System. out.println("Whoa baby, I‘m outta here!" ); } private Object readResolve() { // Return the one true Elvis and let the garbage collector // take care of the Elvis impersonator. return INSTANCE ; } // This code would normally appear outside the class! public static void main(String[] args) { Elvis elvis = Elvis. INSTANCE; elvis.leaveTheBuilding(); } }
标签:
原文地址:http://www.cnblogs.com/ttylinux/p/4355241.html