單例設計模式的要求:
1在某些情況下爲了避免死其他程序過多的該類的對象,則需禁止其他程序建立該類的對象.
2但是又需要讓其他程序能夠訪問到該類的對象,只好在本類中自定義一個對象
3這個自定義對象要被其他程序訪問,就必須在該類中對外提供一些訪問方式
由以上要求,單例模式的設計思路:
1將構造器函數私有化,這樣就可以避免其他程序創建該類的對象.
2在該類中創建一個本來對象
3提供一個方法以便獲取該對象---因爲外界程序無法創建該類對象,所以調用該方法只能通過類名調用的形式來調用方法,所以該方法必須爲static修飾的,要被外界訪問,所以爲public修飾權限
package cn.imust.day;
//單例設計模式
class SingleInstance
{
private int num;
public void setNum(int num){
this.num=num;
}
public int getNum(){
return this.num;
}
//the above Javabean is order to test this Class can only have one instance
//the private constructor
private SingleInstance(){}
//the user-defined instance
private static SingleInstance single =new SingleInstance();
//the method offer to other programs
public static SingleInstance getInstance(){
return single;
}
}
//definite a class to test the Singleton pattern
class TestSingle
{
public static void main(String[] args){
SingleInstance single1=SingleInstance.getInstance();
SingleInstance single2=SingleInstance.getInstance();
single1.setNum(23);
System.out.println(single2.getNum());//the finally output is 23,indicate that the instance is the same one
}
}
具體in using ,we create the class like usually we do ,but when we need the class only have one instance ,just add the three conditions .
There are two methods for creating of Singleton pattern ,the above is one,which called "餓漢式單例設計模式" ,the other is called "懶漢單例設計模式",the key point is also the difference ,look at :
private static SingleInstance single=null;
//the method offer to other programs
public static SingleInstance getInstance(){
if (single==null)
{
single=new SingleInstacne();
}
return single;
}
多線程中的懶漢式單例:
class Single
{
private static Single s=null;
private Single(){}
public static Single getInstance(){//there you may not use the 同步函數,becuase if so,you need to check the 鎖棋標誌 many times,witch will decline the efficiency,so use the 同步代碼塊 like below:
if (s==null)
{
synchronized(Single.class){
if (s==null)
{
s=new Single();
}
}
}
return s;
}
}