packageidv.design.pattern.singleton.enumtype;/** * @author Carl Lu */publicenumSingleton {/* * In "Effective Java", the author said that * "a single-element enum type is the best way to implement a singleton." * * The following line is also like: * "public final static Singleton uniqueInstance = new Singleton();" */ uniqueInstance;publicvoidsingletonOperation() {System.out.println("Singleton operation with instance: "+Singleton.uniqueInstance.hashCode()); }}
自己測看看:
packageidv.design.pattern.singleton.enumtype;/** * @author Carl Lu */publicclassClient {publicstaticvoidmain(String[] args) {for (int i =0; i <5; i++) {Singleton.uniqueInstance.singletonOperation(); } }}