設計模式之_單例模式

單例模式有兩種:一種是:餓漢式  一種是:懶漢式

餓漢式如下:

class Person {
	//1.私有化構造器
	private Person(){
		
	}
	//2.私有化對象
	private static Person instance = new Person();
	//3.提供給外部訪問的方法
	public static Person getInstance(){
		return instance;
	}
}


懶漢式:可能存在線程安全問題,一般情況下,不建議使用

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




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