1. 程式人生 > >設計模式:單例模式-餓漢式 懶漢式

設計模式:單例模式-餓漢式 懶漢式

test 一加 單例 設計模式 餓漢式 private 調用 ati 創建

懶漢模式

class Test{
//懶漢模式 類加載後不創建對象,當調用getTest時才創建對象
//延遲加載
static Test s= null;
private Test(){}
public static Test getTest(){
if(s==null)
s=new Test();
return s;

}
}


------------------------------------------------------------
餓漢模式

class Test1{
//餓漢模式 類一一加載就創建對象,
static Test1 s= new Test1();

private Test1(){}
public static Test1 getTest1(){
return s;
}
}

設計模式:單例模式-餓漢式 懶漢式