• 设计模式之单例模式


    单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

    • 1、单例类只能有一个实例。
    • 2、单例类必须自己创建自己的唯一实例。
    • 3、单例类必须给所有其他对象提供这一实例。
    • 使用场景:

      • 1、要求生产唯一序列号。
      • 2、WEB 中的计数器,不用每次刷新都在数据库里加一次,用单例先缓存起来。
      • 3、创建的一个对象需要消耗的资源过多,比如 I/O 与数据库的连接等。  
      • 单例模式的几种实现方式:

        • 懒汉式,线程不安全

        • public class Singleton {
        • private static Singleton instance;
        • private Singleton (){}
        • public static Singleton getInstance() {
        • if (instance == null) {
        • instance = new Singleton();
        •         }
        • return instance;
        •     }
        • }
        • 懒汉式,线程安全

        • public class Singleton {
        • private static Singleton instance;
        • private Singleton (){}
        • public static synchronized Singleton getInstance() {
        • if (instance == null) {
        • instance = new Singleton();
        • }
        • return instance;
        • } }
        • 饿汉式

        • public class Singleton {
        • private static Singleton instance = new Singleton();
        • private Singleton (){}
        • public static Singleton getInstance() { return instance; } }
        • 双检锁/双重校验锁(DCL,即 double-checked locking)线程安全

        • public class Singleton {
        • private volatile static Singleton singleton;
        • private Singleton (){}
        • public static Singleton getSingleton() {
        • if (singleton == null) {
        • synchronized (Singleton.class) {
        • if (singleton == null) {
        • singleton = new Singleton();
        • } } }
        • return singleton; } }
        • 登记式/静态内部类

        • public class Singleton {
        • private static class SingletonHolder {
        • private static final Singleton INSTANCE = new Singleton();
        • }
        • private Singleton (){}
        • public static final Singleton getInstance() {
        • return SingletonHolder.INSTANCE;
        • } }
        • 枚举

        • public enum Singleton {
        • INSTANCE;
        • public void whateverMethod() { }
        • }
  • 相关阅读:
    html5跨域通讯之postMessage的用法
    zTree插件之多选下拉菜单代码
    css3创建一个上下线性渐变色背景的div
    zTree插件之单选下拉菜单代码
    PhoneGap中navigator.notification.confirm的用法详解
    CCS3属性之text-overflow:ellipsis;的用法和注意之处
    HTML5的自定义属性data-* 的用法解析
    HSSFWorkbook转MultipartFile InputStream转MultipartFile
    @Transactional
    synchronized volatile
  • 原文地址:https://www.cnblogs.com/liufei-90046109/p/11383335.html
Copyright © 2020-2023  润新知