从java1.5版本开始,实现singleton出现了第三种方式:
public enum SingleTon { INSTANCE; public void speak() { System.out.println(this + " is speaking! "); } }
测试代码:
public class SingleTonTest { public static void main(String[] args) throws Exception { SingleTon s1 = SingleTon.INSTANCE; s1.speak(); SingleTon s2 = SingleTon.INSTANCE; s2.speak(); System.out.println(s1 == s2); } } 测试结果: INSTANCE is speaking! INSTANCE is speaking! true