23種設計模式之單例模式-Java語言-(一)

設計模式的分類

  1. 創建型模式:單例模式,抽象工廠模式,原型模式,建造者模式,工廠模式
  2. 結構型模式:適配器模式,橋接模式,裝飾模式,組合模式,外觀模式,享元模式,代理模式
  3. 行爲模式:模板方法模式,命令模式,訪問者模式,迭代器模式,觀察者模式,中介模式,備忘錄模式,解釋器模式,狀態模式,策略模式,職責鏈模式

單例設計模式介紹

核心構造器私有化
所謂類的單例設計模式,就是採取一定的方法保證在整個的軟件系統中,對某個類只能存在一個對象實例,並且該類只提供一個取得其對象實例的方法(靜態方法)。

單例設計模式的八種方式

  1. 餓漢式單例(靜態常量)
  2. 餓漢式(靜態代碼塊)
  3. 懶漢式(線程不安全)
  4. 懶漢式(線程安全,同步方法)
  5. 懶漢式(線程安全,同步代碼塊)
  6. 雙重檢查(DCL)
  7. 靜態內部類
  8. 枚舉
    注意:上面所說單例:除了枚舉採用的創建單例的方法,其他創建的方法都可以通過反射的方法來破壞單例

1.餓漢式單例

  1. 構造器私有化
  2. 類的內部創建對象
  3. 向外暴露一個靜態的公共方法。getInstance
  4. 代碼如下:

靜態變量(可以使用,但不推薦

public class SingletonTest01 {

	public static void main(String[] args) {
		//測試
		Singleton instance = Singleton.getInstance();
		Singleton instance2 = Singleton.getInstance();
		System.out.println(instance == instance2); // true
		System.out.println("instance.hashCode=" + instance.hashCode());
		System.out.println("instance2.hashCode=" + instance2.hashCode());
	}
}
//餓漢式(靜態變量)
class Singleton {
	//1. 構造器私有化, 外部能new
	private Singleton() {	
	}
	
	//2.本類內部創建對象實例
	private final static Singleton instance = new Singleton();
	
	//3. 提供一個公有的靜態方法,返回實例對象
	public static Singleton getInstance() {
		return instance;
	}	
}

靜態代碼塊(可以使用,但不推薦

class Singleton {
	
	//1. 構造器私有化, 外部能new
	private Singleton() {
		
	}
	

	//2.本類內部創建對象實例
	private  static Singleton instance;
	
	static { // 在靜態代碼塊中,創建單例對象
		instance = new Singleton();
	}
	
	//3. 提供一個公有的靜態方法,返回實例對象
	public static Singleton getInstance() {
		return instance;
	}
	
}

總結:

  1. 優點:這種寫法比較簡單,就是在類裝載的時候就完成實例化。避免了線程同步問題。
  2. 缺點:在類裝載的時候就完成實例化,沒有達到LazyLoading的效果。如果從始至終從未使用過這個實例,則會造成內存的浪費
  3. 這種方式基於classloder機制避免了多線程的同步問題,不過,instance在類裝載時就實例化,在單例模式中大多數都是調用getInstance方法,但是導致類裝載的原因有很多種,因此不能確定有其他的方式(或者其他的靜態方法)導致類裝載,這時候初始化instance就沒有達到lazyloading的效果
  4. 結論:這種單例模式可用,可能造成內存浪費
  5. 靜態代碼塊:它只是將實例化的過程放在了靜態代碼塊中,其它的都與靜態常量的方法類似

懶漢式單例(不要使用

代碼:

package com.atguigu.singleton.type3;
public class SingletonTest03 {

	public static void main(String[] args) {
		System.out.println("懶漢式1 , 線程不安全~");
		Singleton instance = Singleton.getInstance();
		Singleton instance2 = Singleton.getInstance();
		System.out.println(instance == instance2); // true
		System.out.println("instance.hashCode=" + instance.hashCode());
		System.out.println("instance2.hashCode=" + instance2.hashCode());
	}

}

class Singleton {
	private static Singleton instance;
	private Singleton() {}
	//提供一個靜態的公有方法,當使用到該方法時,纔去創建 instance
	//即懶漢式
	public static Singleton getInstance() {
		if(instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}

總結:

  1. 起到了LazyLoading的效果(餓漢式單例沒有起到懶加載的效果),但是隻能在單線程下使用。
  2. 如果在多線程下,一個線程進入了if(singleton==null)判斷語句塊,還未來得及往下執行,另一個線程也通過了這個判斷語句,這時便會產生多個實例。所以在多線程環境下不可使用這種方式
  3. 結論:在實際開發中,不要使用這種方式.

懶漢式(線程安全,同步代碼塊)可以使用,但不推薦

package com.atguigu.singleton.type4;
public class SingletonTest04 {
	public static void main(String[] args) {
		System.out.println("懶漢式2 , 線程安全~");
		Singleton instance = Singleton.getInstance();
		Singleton instance2 = Singleton.getInstance();
		System.out.println(instance == instance2); // true
		System.out.println("instance.hashCode=" + instance.hashCode());
		System.out.println("instance2.hashCode=" + instance2.hashCode());
	}
}
// 懶漢式(線程安全,同步方法)
class Singleton {
	private static Singleton instance;
	private Singleton() {}
	//提供一個靜態的公有方法,加入同步處理的代碼,解決線程安全問題
	//即懶漢式
	public static synchronized Singleton getInstance() {
		if(instance == null) {
			instance = new Singleton();
		}
		return instance;
	}
}

總結:

  1. 解決了線程安全問題
  2. 效率太低了,每個線程在想獲得類的實例時候,執行getInstance()方法都要進行同步。而其實這個方法只執行一次實例化代碼就夠了,後面的想獲得該類實例,直接return就行了。方法進行同步效率太低
  3. 結論:在實際開發中,不推薦使用這種方式

雙重檢查(DCL)推薦使用

package com.atguigu.singleton.type6;
public class SingletonTest06 {

	public static void main(String[] args) {
		System.out.println("雙重檢查");
		Singleton instance = Singleton.getInstance();
		Singleton instance2 = Singleton.getInstance();
		System.out.println(instance == instance2); // true
		System.out.println("instance.hashCode=" + instance.hashCode());
		System.out.println("instance2.hashCode=" + instance2.hashCode());	
	}
}
// 懶漢式(線程安全,同步方法)
class Singleton {
	private static volatile Singleton instance;
	private Singleton() {}
	//提供一個靜態的公有方法,加入雙重檢查代碼,解決線程安全問題, 同時解決懶加載問題
	//同時保證了效率, 推薦使用
	public static Singleton getInstance() {
		if(instance == null) {
			synchronized (Singleton.class) {
				if(instance == null) {
					instance = new Singleton();
				}
			}
		}
		return instance;
	}
}

注意使用了volatile關鍵字和synchronized關鍵字
總結:

  1. Double-Check概念是多線程開發中常使用到的,如代碼中所示,我們進行了兩次if(singleton==null)檢查,這樣就可以保證線程安全了。
  2. 這樣,實例化代碼只用執行一次,後面再次訪問時,判斷if(singleton==null),直接return實例化對象,也避免的反覆進行方法同步.
  3. 線程安全;延遲加載;效率較高
  4. 結論:在實際開發中,推薦使用這種單例設計模式

靜態內部類 推薦使用

package com.atguigu.singleton.type7;
public class SingletonTest07 {

	public static void main(String[] args) {
		System.out.println("使用靜態內部類完成單例模式");
		Singleton instance = Singleton.getInstance();
		Singleton instance2 = Singleton.getInstance();
		System.out.println(instance == instance2); // true
		System.out.println("instance.hashCode=" + instance.hashCode());
		System.out.println("instance2.hashCode=" + instance2.hashCode());	
	}
}
// 靜態內部類完成, 推薦使用
class Singleton {
	private static volatile Singleton instance;
	//構造器私有化
	private Singleton() {}
	//寫一個靜態內部類,該類中有一個靜態屬性 Singleton
	private static class SingletonInstance {
		private static final Singleton INSTANCE = new Singleton(); 
	}
	//提供一個靜態的公有方法,直接返回SingletonInstance.INSTANCE
	public static synchronized Singleton getInstance() {
		
		return SingletonInstance.INSTANCE;
	}
}

總結:

  1. 這種方式採用了類裝載的機制來保證初始化實例時只有一個線程。
  2. 靜態內部類方式在Singleton類被裝載時並不會立即實例化,而是在需要實例化時,調用getInstance方法,纔會裝載SingletonInstance類,從而完成Singleton的實例化。
  3. 類的靜態屬性只會在第一次加載類的時候初始化,所以在這裏,JVM幫助我們保證了線程的安全性,在類進行初始化時,別的線程是無法進入的。
  4. 優點:避免了線程不安全,利用靜態內部類特點實現延遲加載,效率高
  5. 結論:推薦使用.

枚舉 推薦使用

package com.atguigu.singleton.type8;
public class SingletonTest08 {
	public static void main(String[] args) {
		Singleton instance = Singleton.INSTANCE;
		Singleton instance2 = Singleton.INSTANCE;
		System.out.println(instance == instance2);
		System.out.println(instance.hashCode());
		System.out.println(instance2.hashCode());
		instance.sayOK();
	}
}
//使用枚舉,可以實現單例, 推薦
enum Singleton {
	INSTANCE; //屬性
	public void sayOK() {
		System.out.println("ok~");
	}
}

總結:

  1. 這藉助JDK1.5中添加的枚舉來實現單例模式。不僅能避免多線程同步問題,而且還能防止反序列化重新創建新的對象。
  2. 這種方式是EffectiveJava作者JoshBloch提倡的方式
  3. 結論:推薦使用

單例模式注意事項和細節說明

  1. 單例模式保證了系統內存中該類只存在一個對象,節省了系統資源,對於一些需要頻繁創建銷燬的對象,使用單例模式可以提高系統性能
  2. 當想實例化一個單例類的時候,必須要記住使用相應的獲取對象的方法,而不是使用new
  3. 單例模式使用的場景:需要頻繁的進行創建和銷燬的對象、創建對象時耗時過多或耗費資源過多(即:重量級對象),但又經常用到的對象、工具類對象、頻繁訪問數據庫或文件的對象(比如數據源、session工廠等)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章