设计模式-单例模式

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


1.饿汉式

  • 构造器私有化(即防止通过new创建对象)
  • 类的内部创建对象
  • 向外暴露一个静态的公共方法(即getInstance方法)
1.1 静态变量
1.1.1 代码实现
public class HungryMan {
    public static void main(String[] args) {
        HungryMan instance1 = HungryMan.getInstance();
        HungryMan instance2 = HungryMan.getInstance();
        System.out.println(instance1 == instance2);  // true
    }
    // 1.构造器私有化
    private HungryMan(){}
    // 2.类的内部创建对象
    private final static HungryMan instance = new HungryMan();
    // 3.向外暴露一个静态的公共方法
    public static HungryMan getInstance(){
        return instance;
    }
}
1.1.2 优缺点
  • 优点:
    • 写法简单
    • 避免了线程同步问题(因为线程每次都只能也必定只可以拿到这个唯一的对象)
  • 缺点:
    • 在类装载的时候就完成实例化(除了getInstance方法,导致类装载有很多方式),没有达到Lazy Loading的效果
    • 如果从未使用过这个实例,则会造成内存的浪费
1.2 静态代码块
1.2.1 代码实现
public class HungryMan {
    public static void main(String[] args) {
        HungryMan instance1 = HungryMan.getInstance();
        HungryMan instance2 = HungryMan.getInstance();
        System.out.println(instance1 == instance2);  // true
    }

    // 1.构造器私有化
    private HungryMan(){}
    // 2.类的内部创建对象
    private final static HungryMan instance;
    static {
        instance = new HungryMan();
    }
    // 3.向外暴露一个静态的公共方法
    public static HungryMan getInstance(){
        return instance;
    }
}
1.2.2 优缺点
  • 优点:
    • 写法简单
    • 避免了线程同步问题,原因如下:
      • 所有的类变量以及static静态代码块,都是在一个叫clinit()的方法里面完成
      • 虚拟机会保证clinit()代码在多线程并发的时候,只会有一个线程可以访问到,其他的线程都需要等待
  • 缺点:
    • 在类装载的时候就完成实例化(除了getInstance方法,还有很多导致类装载的方式),没有达到Lazy Loading的效果
    • 如果从未使用过这个实例,则会造成内存的浪费

2.懒汉式

用到实例采取创建

2.1 线程不安全-普通写法
2.1.1 代码实现
public class LazyMan1 {
    public static void main(String[] args) {
        LazyMan1 instance1 = LazyMan1.getInstance();
        LazyMan1 instance2 = LazyMan1.getInstance();
        System.out.println(instance1 == instance2);  // true
    }

    private static LazyMan1 instance;
    private LazyMan1() {}
    // 提供一个静态的公共方法,使用到该方法才去创建instance
    public static LazyMan1 getInstance() {
        if (instance == null) {
            instance = new LazyMan1();
        }
        return instance;
    }
}
2.1.2 优缺点
  • 优点:起到了Lazy Loading的效果
  • 缺点:线程不安全(假设一个线程进入了if (singleton == null)判断语句块,还未来得及往下执行。另一个线程也通过了这个判断语句,这时便会产生多个实例)
2.2 线程不安全-同步代码块
2.2.1 代码实现
public class LazyMan3 {
    public static void main(String[] args) {
        LazyMan3 instance1 = LazyMan3.getInstance();
        LazyMan3 instance2 = LazyMan3.getInstance();
        System.out.println(instance1 == instance2);  // true
    }

    private static LazyMan3 instance;
    private LazyMan3() {}
    // 提供一个静态的公共方法,但是使用synchronized代码块,使用到该方法才去创建instance
    public static LazyMan3 getInstance() {
        if (instance == null) {
            synchronized (LazyMan3.class) {
                instance = new LazyMan3();
            }
        }
        return instance;
    }

}
2.2.2 优缺点
  • 优点:起到了Lazy Loading的效果
  • 缺点:线程不安全,原因和2.1一样(尽管使用了同步代码块)
2.3 线程安全-同步方法
2.3.1 代码实现
public class LazyMan2 {
    public static void main(String[] args) {
        LazyMan2 instance1 = LazyMan2.getInstance();
        LazyMan2 instance2 = LazyMan2.getInstance();
        System.out.println(instance1 == instance2);  // true
    }

    private static LazyMan2 instance;
    private LazyMan2() {}
    // 提供一个静态的公共方法,但是使用synchronized加在类上,使用到该方法才去创建instance
    public static synchronized LazyMan2 getInstance() {
        if (instance == null) {
            instance = new LazyMan2();
        }
        return instance;
    }
}
2.3.2 优缺点
  • 优点:解决了线程不安全问题
  • 缺点:效率太低,每个线程在想获得类的实例时候,执行getInstance方法都要进行同步

3.双重检查(推荐)

3.1 代码实现
public class DoubleCheck {
    public static void main(String[] args) {
        DoubleCheck instance1 = DoubleCheck.getInstance();
        DoubleCheck instance2 = DoubleCheck.getInstance();
        System.out.println(instance1 == instance2);  // true
    }

    private static volatile DoubleCheck instance;
    private DoubleCheck() {}
    // 提供一个静态的公共方法,加入双重检查代码,使用到该方法才去创建instance
    public static DoubleCheck getInstance() {
        if (instance == null) {
            synchronized (DoubleCheck.class) {
                if (instance == null) {
                    instance = new DoubleCheck();
                }
            }
        }
        return instance;
    }
}
3.2 优点

实例化代码只用执行一次,后面再次访问时,判断if (singleton == null),如果不为空直接return实例化对象,避免的反复进行方法同步

  • 线程安全
  • 延迟加载
  • 效率较高

4.静态内部类(推荐)

4.1 代码实现
public class StaticInnerClass {
    public static void main(String[] args) {
        StaticInnerClass instance1 = StaticInnerClass.getInstance();
        StaticInnerClass instance2 = StaticInnerClass.getInstance();
        System.out.println(instance1 == instance2);  // true
    }

    private StaticInnerClass() {}
    private static class SingtleonInstance {
        private static final StaticInnerClass INSTANCE = new StaticInnerClass();
    }
    // 提供一个静态的公共方法,使用到该方法才去创建instance
    public static StaticInnerClass getInstance() {
        return SingtleonInstance.INSTANCE;
    }
}
4.2 优点
  • 延迟加载:静态内部类方式在StaticInnerClass类被装载时并不会立即实例化,而是在调用getInstance方法,才会装载SingletonInstance类,进而完成StaticInnerClass的实例化
  • 线程安全:采用了类装载的机制来保证初始化实例时只有一个线程(类在初始化的时候别线程无法进入)

5.枚举(推荐)

5.1 代码实现
public class Enum {
    public static void main(String[] args) {
        Singleton instance1 = Singleton.INSTANCE;
        Singleton instance2 = Singleton.INSTANCE;
        System.out.println(instance1 == instance2); // true
    }
}
enum Singleton{
    INSTANCE
}
5.2 优点
  • 避免多线程同步问题
  • 防止反序列化重新创建新的对象

6.应用场景

  • 需要频繁进行创建和销毁的对象
  • 创建对象时耗时过多或耗费资源过多(重量级对象)但又经常用到的对象
  • 工具类对象,如java.lang.Runtime,它采用饿汉式
public class Runtime {
    private static final Runtime currentRuntime = new Runtime();
    public static Runtime getRuntime() {
        return currentRuntime;
    }
    private Runtime() {}
}
  • 频繁访问数据库或文件的对象(如数据源、session工厂)

参考

https://www.bilibili.com/video/BV1G4411c7N4?p=29-38

设计模式【1.3】-- 为什么饿汉式单例是线程安全的?


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值