一、餓漢式:(開發中用)
1、構造方法私有化
2、類對象在本類中創建,並且本實例對象私有化
3、提供公有的static方法獲取該私有實例對象
實例:
/*
* 單例設計模式:餓漢式(開發中用)
* 1、首先在本類中創建一個對象
* 2、本實例私有化
* 3、提供公有的獲取實例的方法
* 4、由於不能在本類以外創建對象,所以只能用類本身調用此公有方法,所以需static修飾此公有方法
*/
public class Student {
//私有化此對象,避免本類以外修改此對象
private static Student student = new Student();
//提供公有的獲取實例的方法,此方法static修飾
public static Student getInstance(){
return student;
}
//構造方法私有化,使得不能在本類以外創建對象
private Student(){}
二、懶漢式:(面試中用)
1、構造方法私有化
2、在本類中先聲明實例對象
3、提供共有的static方法獲取該實例對象
4、在多線程的情景下,該方法可能會被同時調用,所以需加同步synchronized
實例:
//私有化實例對象,使得本類以外不能更改此聲明
private static Person person;
//提供共有的獲取實例的方法,爲避免多線程場景共同調用此方法產生一場,需加同步
public static synchronized Person getInstance(){
if(person == null){
person = new Person();
}
return person;
}
//私有化構造方法,使得本類外不能創建對象
private Person(){}