Java反射与工厂设计模式
程序员文章站
2022-03-09 20:29:44
...
如:传统工厂类
interface IFruit{
void eat();
}
class Apple implements IFruit{
public void eat() {
System.out.println("吃苹果");
}
}
class Orange implements IFruit{
public void eat() {
System.out.println("吃橘子");
}
}
class Factory{
private Factory() {}
public static IFruit getInstance(String name) {
if("apple".equals(name)) {
return new Apple();
}if("orange".equals(name)) {
return new Orange();
}
return null;
}
}
public class Test{
public static void main(String[] args) {
IFruit fruit1 = Factory.getInstance("apple");
fruit1.eat();
IFruit fruit2 = Factory.getInstance("orange");
fruit2.eat();
}
}
特点:每增加一个接口子类就需要修改工厂类。如:利用反射实现工厂类
interface IFruit{
void eat();
}
class Apple implements IFruit{
public void eat() {
System.out.println("吃苹果");
}
}
class Orange implements IFruit{
public void eat() {
System.out.println("吃橘子");
}
}
class Factory{
private Factory() {}
public static IFruit getInstance(String name) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
IFruit fruit = (IFruit) Class.forName(name).newInstance();
return fruit;
}
}
public class Test{
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
IFruit fruit = Factory.getInstance("test4.Apple");
fruit.eat();
}
}
特点:无论增加多少接口子类都不用修改工厂类。