單例設計模式
先初始化對象
對象是方法被調用時才初始化
利用這三步進行代碼實現
提示
代碼說明
//
[java]
class Single
{
private int num;
public void setNum(int num)
{
this
}
public int getNum()
{
return num;
}
//將構造函數私有化
private Single(){}
//在類中創建一個本類對象
private static Single s = new Single()
//提供一個方法可以獲取到該對象
public static Single getInstance()
{
return s;
}
}
class SingleDemo
{
public static void main(String[] args)
{
//單例的構造函數被靜態後不能創建對象
Single s
Single s
s
System
}
}
//
[java]
class Single
{
private static Single s = null;//先建立一個空對象
private Single(){}
public static Single getInstance()
{
if(s==null)//判斷s是否為空
s = new Single()
return s;
}
}
這裡的懶漢式存在安全隱患
[java]
class Single
{
private static Single s = null;
private Single(){}
public static Single getInstance()
{
if(s==null)
{
synchronized(Single
{
if(s==null)
s = new Single()
}
}
return s;
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26060.html