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!

  • 相关阅读:
    Python入门-函数进阶
    Python入门-初始函数
    Leetcode300. Longest Increasing Subsequence最长上升子序列
    Leetcode139. Word Break单词拆分
    Leetcode279. Perfect Squares完全平方数
    Leetcode319. Bulb Switcher灯泡开关
    Leetcode322. Coin Change零钱兑换
    二叉树三种遍历两种方法(递归和迭代)
    Leetcode145. Binary Tree Postorder Traversal二叉树的后序遍历
    Leetcode515. Find Largest Value in Each Tree Row在每个树行中找最大值
  • 原文地址:https://www.cnblogs.com/tjc1996/p/10660894.html
Copyright © 2011-2022 走看看