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

    单例模式是设计模式中使用最为普遍的模式之一,它是一种对象创建模式,单例模式可以确保系统中一个类只产生一个实例,而且自行实例化并向整个系统提供这个实例。

    好处

    1. 节省系统开销,频繁使用的对象,节省创建花费的时间。
    2. 由于创建次数少,内存使用低,减轻GC压力。

    特点

    1. 单例类确保自己只有一个实例。
    2. 单例类必须创建自己的唯一实例。
    3. 单例类必须给所有其他对象提供这一实例。

    饿汉

        public class EagerSingleton {
            private static EagerSingleton instance = new EagerSingleton();
            private EagerSingleton(){
            }
            public static EagerSingleton getInstance(){
                return instance;
            }
        }
    
    构造方法私有,instance成员变量和getInstance()是static,jvm加载时,就会被创建。缺点,不支持lazy-loading,会内存常驻。
    

    懒汉

        public class LazySingleton {
        private static LazySingleton instance = null;
        private LazySingleton(){
        }
        public static LazySingleton getInstance(){
            if(instance == null){
                instance = new LazySingleton();
            }
            return instance;
        }
    }
    
    非线程安全,多个访问者同时访问,则会产生多个实例。
    

    懒汉加锁

        public class LazySingleton {
        private static LazySingleton instance = null;
        private LazySingleton(){
        }
        public static synchronized LazySingleton getInstance(){
            if(instance == null){
                instance = new LazySingleton();
            }
            return instance;
        }
    
    引入了同步关键字保证线程安全,但降低系统性能。
    

    静态内部类

        public class LazySingleton {
        private LazySingleton(){
        }
        private static class SingletonHolder{
           private static LazySingleton instance = new LazySingleton();
        }
    
        public static  LazySingleton getInstance(){
            return SingletonHolder.instance;
        }
    
    调用getInstance()时,才会加载SingletonHolder,从而初始化instance。(静态内部类在第一次使用时才会被加载)
  • 相关阅读:
    由于扩展配置问题而无法提供您请求的页面。如果该页面是脚本,请添加处理程序。
    中晟银泰国际中心酒店式公寓介绍 业主交流QQ群:319843248
    社保关系转移
    在中国,大数据的有效商业模式在哪里?
    指点传媒:在手机上做“精准营销”
    说说大型高并发高负载网站的系统架构【转】
    BI的相关问题[转]
    python 中有趣的库tqdm
    python之字符串操作方法
    比Screen更好用的神器:tmux
  • 原文地址:https://www.cnblogs.com/Ch1nYK/p/8598303.html
Copyright © 2011-2022 走看看