Effective Java Item3:Enforce the singleton property with a private constructor or an enum type

Item3:Enforce the singleton property with a private constructor or an enum type

采用枚举类型(ENUM)实现单例模式。

public enum Elvis {
    INSTANCE;
    
    public void leaveTheBuiding(){
        System.out.println("a single-element enum type is the best way to implement a singleton");
    }
}

使用方式:

Elvis.INSTANCE.leaveTheBuiding();

 

posted @ 2015-02-25 13:09  yshy  阅读(155)  评论(0编辑  收藏  举报