复习
其中登记式注册单例模式:
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 阅读(82)
评论(0) 编辑 收藏