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;
        }
    }
  • 相关阅读:
    国际区号选取组件
    python和js执行字符串函数
    mysql存储过程循环遍历某个表以及事件
    mysql创建远程用户
    ubuntu改文件夹权限
    mysql最大连接数
    MSYS
    Eclipse Java 可视化插件
    你不知道的继承
    vue3.x
  • 原文地址:https://www.cnblogs.com/lzh66/p/13301236.html
Copyright © 2011-2022 走看看