设计模式之单例模式

概念原文

Ensure a class has only one instance, and provide a global point of access to it

概念翻译

确保一个类只有一个实例,并且自行实例化后向整个系统提供这个实例

特点

  • 单例类构造函数私有化。
  • 单例类只能有一个实例。
  • 单例类必须自己创建自己的唯一实例。
  • 单例类必须给所有其他对象提供这一实例。

原理

优点与缺点

优点

  • 在内存里只有一个实例,减少了内存的开销,尤其是频繁的创建和销毁实例(比如管理学院首页页面缓存)。
  • 避免对资源的多重占用(比如写文件操作)。
  • 单例模式设置全局访问点,可以优化和共享资源的访问

缺点

  • 没有接口,不能继承,无法扩展,与开闭原则冲突
  • 一个类应该只关心内部逻辑,而不关心外面怎么样来实例化,与单一职责冲突。

应用场景

  • 需要频繁创建的一些类,使用单例可以降低系统的内存压力,减少 GC。
  • 某类只要求生成一个对象的时候,如一个班中的班长、每个人的身份证号等。
  • 某些类创建实例时占用资源较多,或实例化耗时较长,且经常使用。
  • 某类需要频繁实例化,而创建的对象又频繁被销毁的时候,如多线程的线程池、网络连接池等。
  • 频繁访问数据库或文件的对象。
  • 对于一些控制硬件级别的操作,或者从系统上来讲应当是单一控制逻辑的操作,如果有多个实例,则系统会完全乱套。
  • 当对象需要被共享的场合。由于单例模式只允许创建一个对象,共享该对象可以节省内存,并加快对象访问速度。如 Web 中的配置对象、数据库的连接池等。

项目或框架应用

  • 数据库连接池
  • spring bean作用域
  • spring中ApplicationContext类
  • 线程池类
  • web项目中的配置文件
  • web项目中枚举类

代码实现

单例一共有4种实现方式:

  • 懒汉式
  • 饿汉式
  • 静态内部类
  • 枚举

其中,懒汉式又分为以下五种:

  • 常规版
  • 方法全局锁定
  • 单重检查
  • 双重检查
  • 双重检查+volatile修饰。

饿汉式

在启动时直接进行预加载,一步到位。

优缺点

优点
  • 线程安全
  • 调用效率高
缺点
  • 不能延时加载

代码实现

/**
 * The singleton is loaded when the class is loaded or starts the program.
 * @author luowenxing
 */
public class Hungry {
    private static final Hungry singleton=new Hungry();

    /**
     * @return return already initialized singleton.
     */
    public static Hungry getSingleton(){
        return singleton;
    }
}

懒汉式

常规版

不做特殊任何处理,调用时加载,在多线程时线程不安全,可能会出现多个实例。

优缺点
优点
  • 效率高
  • 可以延时加载
缺点
  • 线程不安全
代码实现
/**
 * Loading singleton when it's used .
 * @author luowenxing
 */
public class Lazy {
    private static Lazy singleton;

    /**
     * This method maybe not safely by concurrent access
     * @return
     */
    public static Lazy getSingleton(){
        if (singleton==null){
            singleton = new Lazy();
        }
        return singleton;
    }
}

方法全局锁定

由于常规不做特殊处理的懒汉式在多线程下是线程不安全的,此处给获取实例的方法加上synchronized关键字,保证多线程情况下依然能获取到单例对象。

优缺点
优点
  • 可以延时加载
  • 线程安全
缺点
  • 效率低
代码实现
/**
 * Loading singleton when it's used.
 * @author luowenxing
 */
public class SafeLazy {

    private static SafeLazy singleton;

    /**
     * The whole method will be locked, all concurrent requests must be invoked after the previous request invoke end .
     * Because of locking the whole method, it will need more time .
     *
     * @return
     */
    public synchronized static SafeLazy getSingletonByLockMehtod() {
        if (singleton == null) {
            singleton = new SafeLazy();
        }
        return singleton;
    }

}

单重检查

上述直接锁定全局方法虽然保证了线程的安全性,但是由于synchronized 同步块范围涵盖了整个方法,导致获取单例的效率不高,从而衍化出单重检查的模式,缩小了synchronized同步范围,但是也无法再保证线程的安全性了。

优缺点
优点
  • 效率比同步整个方法高
  • 延时加载
缺点
  • 线程不安全
代码实现
/**
 * Loading singleton when it's used.
 * @author luowenxing
 */
public class SafeLazy {

    private static SafeLazy singleton;
    
    /**
     * Just locking instantiation code, is faster than locking the whole method.
     * But this lock is in the singleton initialize check code, this method is not safe
     * when a concurrent request has already passed inspection.
     *
     * @return
     */
    public static SafeLazy getSingletonByOnceCheck() {
        if (singleton == null) {
            synchronized (SafeLazy.class) {
                singleton = new SafeLazy();
            }
        }
        return singleton;
    }

}

双重检查

上述衍生的单重检查虽然把效率提高了,但是又出现了线程不安全的弊端,针对这种情况,双重检查应运而生。

优缺点
优点
  • 线程安全(相对的,在不发生指令重排的前提下安全)
  • 可延时加载
缺点
  • 效率比同步方法较高,比单重检查低
代码实现
/**
 * Loading singleton when it's used.
 * @author luowenxing
 */
public class SafeLazy {

    private static SafeLazy singleton;
    
    /**
     * This lock is in the first check code .
     * When concurrent request passed first check, there will be execute second check in the locking block
     * to ensure singleton is just initiated once .
     * This method is faster than locking the whole method, and it ensures thread safe on concurrent access .
     *
     * @return
     */
    public static SafeLazy getSingletonByDoubleCheck() {
        if (singleton == null) {
            synchronized (SafeLazy.class) {
                if (singleton == null) {
                    singleton = new SafeLazy();
                }
            }
        }
        return singleton;
    }
}
线程安全与否剖析

双重检查+volatile修饰

由于双重检查线程安全的不可靠性是由于JMM的指令重排序导致的,此处引入volatile关键字,利用volatile三大特性中的禁止指令重排序来解决上述问题。

优缺点
优点
  • 线程安全
  • 可延时加载
  • 效率相对较高
缺点
代码实现
/**
 * Loading singleton when it's used.
 * @author luowenxing
 */
public class SafeLazy {

    private static volatile SafeLazy singleton;
    
    /**
     * This lock is in the first check code .
     * When concurrent request passed first check, there will be execute second check in the locking block
     * to ensure singleton is just initiated once .
     * This method is faster than locking the whole method, and it ensures thread safe on concurrent access .
     *
     * @return
     */
    public static SafeLazy getSingletonByDoubleCheck() {
        if (singleton == null) {
            synchronized (SafeLazy.class) {
                if (singleton == null) {
                    singleton = new SafeLazy();
                }
            }
        }
        return singleton;
    }
}

懒汉式效率排序:常规版>单重检查>双重检查>双重检查+volatile修饰>方法全局锁定

懒汉式线程安全排序:方法全局锁定=双重检查+volatile修饰>双重检查>单重检查>常规版

静态内部类

在单例类的内部声明静态内部类,由静态内部类提供单例类的单例对象。此类实现方式依赖的是static的全局统一性和静态内部类的延时加载。

优缺点

优点
  • 线程安全
  • 调用效率高
  • 可延时加载
缺点

代码实现

/**
 * The singleton is provided by static inner class, it will load lazily .
 * @Author: luowenxing
 */
public class StaticInnerClazz {

    /**
     * Inner class must be guaranteed to be privatized.
     * Static inner classes are loaded only when used.
     */
    private static class SingletonInstance {
        private static final StaticInnerClazz instance = new StaticInnerClazz();
    }

    private StaticInnerClazz() {
    }

    public static StaticInnerClazz getInstance() {
        return SingletonInstance.instance;
    }
}

枚举

java 1.5之后引入的特性,枚举的每一个属性都是单例。

优缺点

优点
  • 线程安全
  • 调用效率高
  • 天然的防止反射和反序列化调用
缺点
  • 不能延时加载

代码实现

/**
 * Enumeration classes are natural singletons.
 * @Author: luowenxing
 */
public enum  SingletonEnum {

    /**
     * Each of its elements is a singleton
     */
    SINGLETON;

    SingletonEnum(){

    }
}

知识拓展

  • 静态内部类的加载过程:静态内部类的加载不需要依附外部类,在使用时才加载。不过在加载静态内部类的过程中也会加载外部类。
  • volatile三大特性: 可见性、不保证原子性、 禁止重排序
  • Java内存模型(Java Memory Model ,JMM)就是一种符合内存模型规范的,屏蔽了各种硬件和操作系统的访问差异的,保证了Java程序在各种平台下对内存的访问都能保证效果一致的机制及规范。是围绕着在并发过程中如何处理可见性、原子性、有序性这三个特性而建立的模型。

相关面试题

  1. Q:什么是单例模式?
    A:确保一个类只有一个实例,并且自行实例化后向整个系统提供这个实例。

  2. Q:单例模式的特点
    A:

  • 单例类构造函数私有化
  • 单例类只能有一个实例。
  • 单例类必须自己创建自己的唯一实例。
  • 单例类必须给所有其他对象提供这一实例。
  1. Q: 单例模式有几种?手写其中XXX
    A:见上述文章。
    4.Q:单例可以被破坏吗?
    A:clone、反射都可以
  2. Q:单例的双重检查是什么?
    A:见上述文章
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lwx-apollo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值