zoukankan      html  css  js  c++  java
  • 研磨设计模式学习笔记4单例模式Signleton

    大纲:

    1. 5种常见单例模式

    一、5种常见单例模式

    1.1饿汉式

    最简单是单例实现

    public class Singleton
    {
        private Singleton (){
            //加载配置文件....
        }
        private static Singleton singleton = new Singleton();
        public static Singleton getInstance(){
            return singleton;
        }
    }

    1.2懒汉式

    懒汉比恶汉多了懒加载的思想

    public class Singleton
    {
        private Singleton (){
            //加载配置文件....
        }
        private static Singleton singleton = null;
        public static Singleton getInstance(){
            if(singleton==null){
                singleton = new Singleton();
            }
            return singleton;
        }
    }

    1.3双检锁(DCL单例)

    上面懒汉式存在线程安全问题,可以利用双重检查加锁避免。

    public class Singleton
    {
        private Singleton (){
            //加载配置文件....
        }
        private volatile static Singleton singleton = null;
        public static Singleton getInstance(){
            if(singleton==null){
                synchronized (Singleton.class){
                    if(singleton==null){
                        singleton = new Singleton();
                    }
                }
            }
            return singleton;
        }
    }

    1.4静态内部类

    DCL这种方式解决了线程安全为题,但用了volatile,效率降低,用静态内部类可以解决这一问题。

    public class Singleton
    {
        private Singleton (){
            //加载配置文件....
        }
        private static class SingletonHolder{
            private static Singleton singleton = new Singleton();
        }
        public static Singleton getInstance(){
            return SingletonHolder.singleton;
        }
    }

    1.5枚举

    effective java推荐的一种单例模式

    public enum  Singleton
    {
        instance;
        Singleton(){
            //加载配置文件....
        }
    }
  • 相关阅读:
    RF学习笔记
    解决pycharm下git命令使用时中文显示乱码
    Django2.2 学习笔记1-概念篇
    cookie、session、token的理解
    win10下安装与使用mysql
    Redis学习笔记
    MongoDB与pymongo学习笔记
    记:打开Charles后,win10 chrome访问https的网站提示“您的链接不是私密链接”的解决过程
    charles抓包教程
    jmeter遍历时间戳
  • 原文地址:https://www.cnblogs.com/liuboyuan/p/9651298.html
Copyright © 2011-2022 走看看