工厂模式(依赖反射)
程序员文章站
2022-03-09 21:44:50
...
工厂方法:
public class HumanFactory2 {
public static Human getHuman(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class clazz = Class.forName(className);
return (Human)clazz.newInstance();
}
}
human和实现类
public interface Human {
void say();
}
public class WhilteHuman implements Human {
@Override
public void say () {
System.out.println(“我是白种人”);
}
}
public class YellowFactory implements Human {
@Override
public void say() {
System.out.println(”我是黄种人”);
}
}
测试类:
public class TestSimpleFactory {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
Human human = HumanFactory2.getHuman("simpleFactory.human.WhiteHuman");
human.say();
}
}
上一篇: time模块常用操作