从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 

 

posted on 2017-08-11 16:36  十七年蝉  阅读(162)  评论(0编辑  收藏  举报