復(fù)習(xí)
其中登記式注冊(cè)單例模式:
import java.util.*;
class Single{
private static HashMap hashmap = new HashMap();
private int number = 0;
static{
Single single = new Single();
hashmap.put(single.getClass().getName(),single);
}
private Single(){}
public static Single getInstance(String name){
if(name == null){
name = "Single";
}
if(hashmap.get(name) == null){
try{
hashmap.put(name,Class.forName(name).newInstance());
}catch(Exception e){
System.out.println(e.getMessage());
}
}
return (Single)hashmap.get(name);
}
public void fun(){
number++;
System.out.println("the is the single fun :" + number);
}
}
他的另外一個(gè)做法是同過(guò)繼承,通過(guò)父類來(lái)注冊(cè)子類的對(duì)象:
代碼如:
class SingleChild extends Single{
public SingleChild(){}
public static SingleChild getInstance(){
return (SingleChild)Single.getInstance("SingleChild");
}
public void fun(){
System.out.println("singlechild");
}
}
當(dāng)它要這樣做之后就破壞了父類,因?yàn)樽宇愐{(diào)用父類的構(gòu)造子函數(shù),所以父類的構(gòu)造子函數(shù)就不能夠?yàn)樗接械模@就破壞單例模式的優(yōu)點(diǎn)。
posted on 2005-07-30 21:04
sky 閱讀(83)
評(píng)論(0) 編輯 收藏