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

    模式:创建型模式
    特点:

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

    ✨ 例子1_懒汉模式
    延迟加载,线程不安全

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

    ✨ 例子2_懒汉模式
    延迟加载,线程安全

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

    ✨ 例子3_饿汉模式
    懒汉模式,线程安全

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

    ✨ 例子4_双检锁/双重校验锁(DCL,即 double-checked locking)
    延迟加载,线程安全

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

    ✨ 例子5_登记式/静态内部类
    延迟加载,线程安全。因为静态内部类和外部类的静态变量,静态方法一样,只要被调用了都会让外部类的被加载。不过不过当只调用外部类的静态变量,静态方法时,是不会让静态内部类的被加载。
    所以我们可以使用这一点达到lazy load

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

    ✨ 例子6
    非延迟加载,线程安全。除此之外,它不仅能避免多线程同步问题,而且还自动支持序列化机制,防止反序列化重新创建新的对象,绝对防止多次实例化。

    public enum Singleton {
    	
    	INSTANCE;
    
    	public void whateverMethod() {
    
    	}
    }
    

    ✨ ps
    他们总说,你还年轻,可以慢点来。可是为啥我总感觉我已经不够时间了!所以,fight!

  • 相关阅读:
    c#将 1, 2, ..., 9共 9 个数字分成 3 组
    信息学院本科生创新项目总结
    Element-ui的使用
    fastmock接口管理
    mock安装与使用
    开闭原则
    里氏替换原则
    依赖倒置原则
    接口隔离原则
    单一职责原则
  • 原文地址:https://www.cnblogs.com/tjc1996/p/10660894.html
Copyright © 2011-2022 走看看