使用静态工场模式,就是通过给工场提出对应的要求,通过调用工场的对应的静态方法来创建我们所需要的对象,工场的内部实现可以调用构造方法也可以通过反射来实现
如下:首先定义抽象类Food,它有二个实现类Rice和Apple,
package com.zcj. factorypattern;
public abstract class Food {
public abstract void print();
}
package com.zcj.staticpattern;
public class Rice extends Food {
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println("i am rice");
}
}
package com.zcj.staticpattern<span style="font-family: Arial, Helvetica, sans-serif;">;</span>
public class Apple extends Food{
@Override
public void print() {
// TODO Auto-generated method stub
System.out.println("i am apple");
}
}
下面是工场的定义:
package com.zcj.staticfactorypattern;
public class FoodFactory {
public static Food createFood(String type) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
if(type=="rice"){
return (Food) Class.forName("com.zcj.abstracfactorypattern.Rice").newInstance();
}
else{
return (Food) Class.forName("com.zcj.abstracfactorypattern.Apple").newInstance();
}
}
}
最下面是我们的测试程序:
package com.zcj.staticfactorypattern;
public class StaticFactoryTest {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Food food =FoodFactory.createFood("apple");
food.print();
}
}