• 单例模式七种写法


    定义

    保证一个类仅有一个实例,并提供一个访问它的全局访问点

    七种写法

    1.饿汉式(简洁直观)

    public class Singleton {
        private static final Singleton INSTANCE = new Singleton();
    
        private Singleton() {
        }
    
        public static Singleton getInstance() {
            return INSTANCE;
        }
    }
    

    2.枚举(饿汉式的变种,最简洁)

    public enum  Singleton {
        INSTANCE;
    }
    

    枚举类型默认构造是私有的

    3.静态代码快(饿汉式的变种,适合复杂的实例化(如外部资源导入等))

    public class Singleton {
        private static final Singleton INSTANCE;
        
        private Singleton(){
        }
    
        static {
           INSTANCE = new Singleton();
        }
        
        public static Singleton getInstance() {
            return INSTANCE;
        }
    }
    

    4.懒汉式(线程不安全,适用于单线程)

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

    5.双重检测锁(DCL,懒汉式的改进,实现线程安全(同步),适用于多线程)

    public class Singleton {  
    	private static volatile Singleton instance = null;  
        
    	private Singleton (){
    	}   
        
    	public static Singleton getInstance() {  
            if (instance == null) {
                synchronized (Singleton.class) {
                    if (instance == null) {
                        instance = new Singleton();
                    }
                }
            }
    		return instance;  
    	}  
    }  
    

    6.静态内部类(懒汉式的改进,适用于多线程)

    public class Singleton {
        private Singleton() {
        }
    
        private static class InnerClass {
            private static final Singleton INSTANCE = new Singleton();
        }
    
        public static Singleton getInstance() {
            return InnerClass.INSTANCE;
        }
    }
    

    7.容器(懒汉式的一种,适用于多线程)

    public class Singleton {
        private static Map<String,Object> map=new HashMap<String, Object>();
        
        private Singleton(){
        }
        
        public static void registerService(String key,Object instance){
            if (!map.containsKey(key)){
                map.put(key,instance);
            }
        }
        
        public static Object getService(String key){
            return map.get(key);
        } 
    }
    
  • 相关阅读:
    第二十二章 6未命名的命名空间 简单
    第二十二章 4使用关键字using 简单
    第二十三模板 3具体化函数模板 简单
    第二十二章 2创建命名空间 简单
    第二十三模板 7复杂类模板 简单
    第二十二章 3使用命名空间 简单
    第二十二章 1什么是命名空间 简单
    第二十三模板 2重载模板 简单
    第二十三模板 1什么是模板 简单
    测定事务引擎设计的基准
  • 原文地址:https://www.cnblogs.com/MessiXiaoMo3334/p/12433759.html
Copyright © 2020-2023  润新知