使用单元素枚举实现单例

如果不涉及到线程安全及延迟加载,单例最简单的写法:

public class SingletonTest {
    public static SingletonTest instance = new SingletonTest();
    private SingletonTest(){
        
    }
}

考虑到线程安全跟延迟加载,修改如下:

public class SingletonTest {
    public static SingletonTest getInstance(){
        return SingletonTestHolder.instance;
    }
    private SingletonTest(){
        
    }
    static class SingletonTestHolder{
        private static final SingletonTest instance = new SingletonTest();
    }
}

这段代码不能解决反射攻击,及序列化的时候,readobject会返回新的对象,需要添加readResolve()方法,并且需要声明所有实例域都是transient(参考effective java第二章)

可以通过单元素枚举来解决以上问题:

public enum SingletonTest {
    instance;
    private int otherField;
}

缺点就是使用enum,无法使用类原本的功能比如继承。所以在合适的场合选择合适的单例写法吧

posted @ 2015-01-03 00:16  huliangbin  阅读(406)  评论(0编辑  收藏  举报