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!

  • 相关阅读:
    数据准备2 数据清洗
    数据准备1 数据导入、导出
    数据分析基本流程 Python基本数据类型 Python各种括号的使用方式
    fineBI 学习成果展示1
    未确认融资收益的计算
    合同现金流量
    公允价值持续计算的金额
    发放股票股利
    权益法未实现内部交易损益的调整
    营业外收入入不入损益
  • 原文地址:https://www.cnblogs.com/tjc1996/p/10660894.html
Copyright © 2011-2022 走看看