2021-03-25

单例设计模式的不同实现方式

类的单例设计模式是指采取一定的方法保证在整个的软件系统中,对某个类只能存在一个实例对象,并且该类只提供一个取得其对象的实例方法(静态方法)。

1.饿汉式

1-1:饿汉式(静态常量)

该方式在类装载时候完成实例化,避免线程同步问题,如果自始至终未使用,会造成内存资源的浪费。

class Singleton{
    //构造器私有化
    private Singleton(){
    }
    //类内部创建实例
    private final static Singleton instance = new Singleton();
    //获取实例
    public static Singleton getInstance(){
        return instance;
    }
}

1-2:饿汉式(静态代码块)

优缺点同上

class Singleton {
    //构造器私有化
    private Singleton() {
    }
    private  static Singleton instance;
    //类内部创建对象
    static{
        instance = new Singleton();
    }
    //返回实例对象
    public static Singleton getInstance(){
        return instance;
    }
}

2.懒汉式

2-1:懒汉式(线程不安全)

能够解决饿汉式资源浪费问题,但是只能在单线程中使用,在实际开发中存在多线程环境,会存在线程安全问题,不要使用此方式。

class Singleton {
    //构造器私有化
    private Singleton() {
    }
    private  static Singleton instance;
    //提供一个人静态公有方法,使用时才创建instance
    public static Singleton getInstance(){
       if(instance == null){
           instance = new Singleton();
       }
       return instance;
    }
}

2-2:懒汉式(线程安全的)

解决了线程不安全问题,但是每个线程在执行getInstance()方法时都要进行同步,效率太低,在实际开发中不推荐。

class Singleton {
    //构造器私有化
    private Singleton() {
    }
    private static Singleton instance;
    //提供一个人静态公有方法,使用时才创建instance,加入了同步处理代码synchronized,解决线程安全问题
    public static synchronized Singleton getInstance(){
       if(instance == null){
           instance = new Singleton();
       }
       return instance;
    }
}

3.双重检查

为了既解决线程安全问题,又解决效率低下的问题,可以采用如下方式,推荐使用。

class Singleton {
    //构造器私有化
    private Singleton() {
    }
    private static volatile Singleton instance;

    //提供一个人静态公有方法,使用时才创建instance,加入了同步处理代码,解决线程安全问题
    public static Singleton getInstance(){
       if(instance == null){
           synchronized (Singleton.class){
                if(instance == null){
                   instance = new Singleton();
               }
           }
       }
       return instance;
    }
}

4.静态内部类实现

线程安全,节约资源,推荐使用

class Singleton {
    //构造器私有化
    private Singleton() {
    }
    
    private static class SingleInstance{
        private static final Singleton INSTANCE = new Singleton();
    }
    
    public static Singleton getInstance(){
       return SingleInstance.INSTANCE;
    }
}

5.枚举实现

能够避免多线程同步问题,还能防止反序列化重新创建新的对象,推荐使用。

enum Singleton{
    INSTANCE;
    public void method(){  
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值