设计模式 之 单例 模式

来源:互联网 发布:ubuntu u盘安装教程 编辑:程序博客网 时间:2024/06/05 16:00

设计模式是开发中很重要的一种思想,今天记录一下单例模式,备忘,哈哈。

first 懒汉式 + 双重校验锁 + 禁止指令重排序优化

public class SingletonOne {// volatile 禁止指令重排序优化private static volatile SingletonOne instance = null;private SingletonOne() {}// synchronized 修饰的同步方法比一般的方法要慢很多。所以此处使用双重校验锁。public static SingletonOne getInstance() {    if (null == instance) {        synchronized(SingletonOne.class) {            if (null == instance) {                instance = new SingletonOne();            }        }    }    return instance;}}

second 饿汉式 不推荐

public class SingletonTwo {private static SingletonTwo instance = new SingletonTwo();private SingletonTwo() {}public static SingletonTwo getInstance() {    return instance;}}

third 静态内部类加载

public class SingletonThree {private SingletonThree() {}private static class SingletonHolder {    public static SingletonThree instance = new  SingletonThree();}public static SingletonThree getInstance() {    return SingletonHolder.instance;}}

fourth 枚举 目前最为安全的实现单例的方法是通过内部静态enum的方法来实现,因为JVM会保证enum不能被反射并且构造器方法只执行一次。

public class SingletonFour {private SingletonFour() {}private static enum Singleton{    INSTANCE;    private SingletonFour instance;    private Singleton() {        instance = new SingletonFour();    }    public SingletonFour getInstance() {        return instance;    }}public static SingletonFour getInstance() {    return Singleton.INSTANCE.instance;}}上面提到的三种实现单例的方式都有共同的缺点:1.需要额外的工作来实现序列化,否则每次反序列化一个序列化的对象时都会创建一个新的实例。2.可以使用反射强行调用私有构造器(如果要避免这种情况,可以修改构造器,让它在创建第二个实例的时候抛异常)。而枚举类很好的解决了这两个问题,使用枚举除了线程安全和防止反射调用构造器之外,还提供了自动序列化机制,防止反序列化的时候创建新的对象。因此,《Effective Java》作者推荐使用的方法。不过,在实际工作中,很少看见有人这么写。
原创粉丝点击