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;
        }
    }

     

  • 相关阅读:
    规则引挚NxBRE文档纪要在流引挚与推论引挚取舍
    去除特殊字符
    C文件操作
    计算球面上两点弧长
    已知圆心和两点画圆弧(算法)(计算机图形)(C#)
    摄像机矩阵变换
    DX之“HelloWord”
    绘制箭头
    绘制二维图片
    绘制三角形
  • 原文地址:https://www.cnblogs.com/hellojava404/p/13150544.html
Copyright © 2011-2022 走看看