Java設計模式之單例模式(筆記)

定義:單例,單個實例,也就是說一個類只能獲取一個實例。

類別:餓漢模式懶漢模式(不考慮線程安全問題)

實現方式:通常在獲取類的實例時,是用new來獲取,new一次,獲取一次實例,如何保證只能獲取一次實例呢?

1.首先要保證外部不能使用new xxx()的方式來獲取實例,給xxx類的構造方法私有化。

2.構造方法一旦私有化,外部就不可訪問,需提供一個公共的方法來獲取該類的實例,而且這個方法不能是實例調用的方法(不能夠通過創建該類的實例調用此方法),應該是一個類方法。

3.要保證獲取的實例是唯一的,需要在類一經加載的時候就創建實例,類只會加載一次,實例也就只會創建一次。

餓漢模式實現方式:

/**
 * @ClassName: SingletonHunger
 * @Description: (餓漢模式)
 * @author: 阿Q
 * @date 2019年9月5日
 *
 */
public class SingletonHunger {
	
	//3.如何保證實例唯一?類一加載的時候,就創建對象,而且只會創建一次對象,這樣就能保證實例唯一
	private static SingletonHunger instance=new SingletonHunger();
	
	//1.首先保證不能使用new XXX()來創建實例,把構造函數設置爲外部不可訪問
	private SingletonHunger(){ 
	}
	//2.外部不可訪問,怎麼創建實例呢?需提供一個對外方法,通過該方法獲取實例;而且這個方法不能是實例的方法(不能夠創建實例來調用方法),只能設置爲類方法
	public static SingletonHunger getInstance(){
		return instance;
	}
	
}

懶漢模式實現方式(不考慮線程安全問題):

/**
 * @ClassName: SingletonLazy
 * @Description: (懶漢模式)
 * @author: 阿Q
 * @date 2019年9月5日
 *
 */
public class SingletonLazy {
	
	private static SingletonLazy instance = null;
	
	private SingletonLazy(){}
	
	public static SingletonLazy getInstance(){
		if(instance==null){
			instance=new SingletonLazy();
		}
		return instance;
	}
}

測試獲取的實例是否唯一:

public class Test {
	
	public static void main(String[] args) {		
		SingletonHunger singleton1 = SingletonHunger.getInstance();
		SingletonHunger singleton2 = SingletonHunger.getInstance();
		if(singleton1==singleton2){
			System.out.println("true");
		}else{
			System.out.println("false");
		}
		
		SingletonLazy singleton3 = SingletonLazy.getInstance();
		SingletonLazy singleton4 = SingletonLazy.getInstance();
		if(singleton3==singleton4){
			System.out.println("true");
		}else{
			System.out.println("false");
		}
	}
}

打印結果:

true
true

懶漢模式和餓漢模式的區別:

餓漢模式:類一經加載就會創建實例,浪費內存,線程安全。

懶漢模式:需要使用時纔會創建實例,但是線程不安全。關於懶漢模式的線程安全的實現方式,待補充。。

 

更深層次的應用可參考博客:

https://blog.csdn.net/justloveyou_/article/details/64127789

https://www.cnblogs.com/awkflf11/p/9906431.html

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章