復習
其中登記式注冊單例模式:
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);
}
}
他的另外一個做法是同過繼承,通過父類來注冊子類的對象:
代碼如:
class SingleChild extends Single{
public SingleChild(){}
public static SingleChild getInstance(){
return (SingleChild)Single.getInstance("SingleChild");
}
public void fun(){
System.out.println("singlechild");
}
}
當它要這樣做之后就破壞了父類,因為子類要調用父類的構造子函數,所以父類的構造子函數就不能夠為私有的,這就破壞單例模式的優點。
posted on 2005-07-30 21:04
sky 閱讀(83)
評論(0) 編輯 收藏