应用Factory模式:一个类(接口)有多个子类
1.静态工厂方法
你会建立一个专门生产Sample实例的工厂:
public class Factory{
public static Sample creator(int which){
//getClass 产生Sample 一般可使用动态类装载装入类。
if (which==1)
return new SampleA();
else if (which==2)
return new SampleB();
}
}
//Sample 是父类,SampleA,SampleB是子类
2.抽象工厂
工厂模式中有: 工厂方法(Factory Method) 抽象工厂(Abstract Factory).
public abstract class Factory{
public abstract Sample creator();
public abstract Sample2 creator(String name);
}
public class SimpleFactory extends Factory{
public Sample creator(){
.........
return new SampleA
}
public Sample2 creator(String name){
.........
return new Sample2A
}
}
public class BombFactory extends Factory{
public Sample creator(){
......
return new SampleB
}
public Sample2 creator(String name){
......
return new Sample2B
}
}
--------------------------------------------------------------------
Class c = Class.forName(className);
factory = (ForumFactory)c.newInstance();
//用类名来实例化一个对象,想换一个实例,只需要改变className