设计模式之单例的N种实现

单例模式是一种常用的设计模式,单例模式的定义是单例的类只允许一个实例存在。

单例的实现主要是通过以下两个步骤:

1.将该类的构造方法定义为私有,这样其他类的代码就无法通过调用该类的构造方法来实例化该类的对象,只能通过该类提供的静态方法来获取该类的实例化对象。

2.在类中定义一个静态方法,当调用该静态方法的时候判断该类持有的对象是否为空,如果不为空则返回其引用,如果

类持有的引用为空则创建一个该类的实例并且将其引用赋予该类的保持的引用。

1.饿汉式(静态常量和静态代码块)

//静态常量
public class Singleton {

    private final static Singleton INSTANCE = new Singleton();

    private Singleton(){}

    public static Singleton getInstance(){
        return INSTANCE;
    }
}

//静态代码块
public class Singleton {

    private static Singleton instance;

    static {
        instance = new Singleton();
    }

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

优点:在类加载的时候完成了实例化,避免了线程安全的问题。

缺点:类加载的时候完成实例化,没有达到Lazy Loading的效果,如果该实例没有被使用,可能会造成内存资源的浪费。

2.懒汉式(非线程安全和线程安全)

非线程安全,只能用于单线程的环境下,如果在线程1判断后失去CPU时间片,线程2获得CPU时间片进行判断,此时的引用判断为空,线程2创建了一个实例,此时线程1获得CPU时间片,则线程1又创建一个实例,此时无法实现单例。

//非线程安全
public class Singleton {

    private static Singleton singleton;

    private Singleton() {}

    public static Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}

线程安全(效率较低)

//线程安全,但是对方法使用synchronized效率较低
public class Singleton {

    private static Singleton singleton;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (singleton == null) {
            singleton = new Singleton();
        }
        return singleton;
    }
}

3.双重检查锁

public class Singleton {

    private static volatile Singleton singleton;

    private Singleton() {}

    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class) {      //1
                if (singleton == null) {          //2
                    singleton = new Singleton();  //3
                }
            }
        }
        return singleton;
    }
}

在双重检查锁中第二次在synchronized代码块中对singleton进行非空检查是为了解决类似于懒汉模式下非线程安全的问题,保证在多线程的情况下可以实现单例。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值