简单工厂指实现统一的接口,编写不同的实现类去实现不同的创建,在创建对象的时候在工厂中通过反射加多态的方式去创建对象。
首先统一接口:
public interface Fruit {
void get();
}
不同的实现类:
public class Apple implements Fruit{
@Override
public void get() {
System.out.println("生产苹果");
}
}
public class Banana implements Fruit{
@Override
public void get() {
System.out.println("生产香蕉");
}
}
在工厂中统一创建:
public class FruitFactory {
public static Fruit get(String type) {
try {
return (Fruit) Class.forName("simplefactory."+type).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
System.out.println("生产失败");
e.printStackTrace();
return null;
}
}
}
通过反射加载去创建对象。
测试类:
public class Test {
public static void main(String[] args) {
Fruit apple = FruitFactory.get("Apple");
Fruit banana = FruitFactory.get("Banana");
apple.get();
banana.get();
}
}