1.单例模式概述

单例模式就是确保类在内存中只有一个对象,该实例必须自动创建,并且对外提供。

2.优缺点

优点:在系统内存中只存在一个对象,因此可以节约系统资源,对于一些需要频繁创建和销毁的对象单例模式无疑可以提高系统的性能。

缺点:没有抽象层,因此扩展很难。职责过重,一定程度上违背了单一职责。

3.饿汉式

public class Singleton {

    //1.构造方法私有化
    private Singleton() {
    }

    //2.创建类的唯一实例,用private static 修饰,不让外界直接访问
    private static Singleton instance = new Singleton();

    //3.提供一个获取上面创建的实例的方法,用public static修饰
    public static Singleton getInstance() {
        return instance;
    }
}

4.懒汉式

public class Singleton {

    //构造方法私有化
    private Singleton() {
    }

    //延迟加载
    private static Singleton instance = null;

    //方式1:需要加同步,否则多线程会有安全问题。这种方式每次进来都会判断锁
    public synchronized static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }

    //方式2:需要加同步,否则多线程会有安全问题。这种方式避免每次进来都会判断锁
    public static Singleton getSingleton() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

 

相关文章:

  • 2021-07-31
  • 2021-06-08
  • 2021-10-02
  • 2021-06-29
  • 2022-02-12
猜你喜欢
  • 2021-10-25
  • 2021-11-29
  • 2021-05-18
  • 2022-12-23
  • 2021-12-17
  • 2021-11-15
  • 2021-11-09
相关资源
相似解决方案