反射与工厂设计模式
程序员文章站
2022-03-01 15:11:32
...
一、定义接口
interface IFuit{
void eat();
}
二、定义类实现接口
class Apple implements IFuit{
@Override
public void eat() {
System.out.println ("吃苹果" );
}
}
class Orange implements IFuit{
@Override
public void eat() {
System.out.println ("吃橘子" );
}
}
class FruitFactory{
private FruitFactory(){
}
public static IFuit getFuitInstance(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class classz = Class.forName ( className );
return (IFuit) classz.newInstance ();
}
}
三、测试
public class Test {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException { ;
IFuit fuit=FruitFactory.getFuitInstance ( "反射.Apple" );
fuit.eat ();
}
}
四、运行结果
上一篇: 设计模式 - 抽象工厂+反射
下一篇: 选择排序