zoukankan      html  css  js  c++  java
  • 单例模式

    顾名思义,单例模式就是要求只有一个实体对象。

    单例模式分为懒汉式和饿汉式

    饿汉式:一开始就创建对象,线程安全,但是如果用不到这个对象,会造成浪费

    懒汉式:要的时候才创建,不会造成浪费,但是会有线程安全的问题.

    饿汉式和懒汉式都是私有化构造函数,不让外面能够直接new 对象.

    饿汉式

    private static Hungry instance = new Hungry();
    
        private Hungry(){}
    
    
        public Hungry getInstance(){
            return instance;
        }

    懒汉不安全式

    public class LazyUnSafe {
    
        private LazyUnSafe instance;
    
        public LazyUnSafe getInstance(){
            if(instance == null){
                instance = new LazyUnSafe();
            }
            return instance;
        }
    }

    懒汉安全式

    public class LazySafe {
    
        private LazySafe instance;
    
        private LazySafe(){}
    
        public LazySafe getInstance() {
            if(instance == null){
                synchronized (LazySafe.class){
                    if(instance == null){
                        instance = new LazySafe();
                    }
                    return instance;
                }
            }
            return instance;
        }
    }
  • 相关阅读:
    VSCode配置Python开发环境
    图像特征——边缘
    关于相机内参中的焦距fx和fy
    摄影变换和仿射变换
    为什么要引入齐次坐标
    链表一
    从小问题看懂链表
    类与对象
    排序一
    数组
  • 原文地址:https://www.cnblogs.com/lzh66/p/13301236.html
Copyright © 2011-2022 走看看