zoukankan      html  css  js  c++  java
  • 单例

    什么是单例?

    单例类在整个程序中只能有一个实例,这个类负责创建自己的对象,并确保只有一个对象被创建

    代码实现要点

    • 私有构造方法

    • 只有该类属性

    • 对外提供获取实例的静态方法

    //饿汉
    public class Singleton {
        //提供私有构造方法
        private Singleton() {}
    ​
        //一出来,就加载创建
        private static Singleton instance = new Singleton();
        
        public static Singleton getInstance(){
            return instance;
        }
    }
    //懒汉
    public class Singleton {
        //提供私有构造方法
        private Singleton() {}
        //第一次使用,才加载创建
        private static Singleton instance = null;
        
        public static synchronized Singleton getInstance() {
            if (instance == null) {
                instance = new Singleton();
            }
            return instance;
        }
    }

    懒汉模式效率低下

    双检锁/双重校验锁(DCL,即 double-checked locking)

    安全且在多线程情况下能保持高性能

    //双检锁
    public class Singleton {
    ​
        private Singleton() {}
        
        private static Singleton instance = null;
        
        public static Singleton getInstance() {
            if (instance == null) {
                synchronized (Singleton.class) {
                    if (instance == null) {
                        instance = new Singleton();
                    }
                } 
            }
            return instance;
        }
    }

     

  • 相关阅读:
    db.Exec和db.Query的区别
    golang两种get请求获取携带参数的方式
    gin实现中间件middleware
    gin操作session
    笔札-有触动的句子
    并发的基本概念
    售货员的难题
    传球游戏之最小总代价
    状压dp入门
    [COCI 2010] OGRADA
  • 原文地址:https://www.cnblogs.com/hellojava404/p/13150544.html
Copyright © 2011-2022 走看看