工厂设计模式,用户不需要关注接口的具体子类实例是哪个,用户只需要按照固定格式传入相应的参数,程序返回相应的子类实例。
interface Fruit{
public void eat();
}
class Apple implements Fruit{
@Override
public void eat() {
System.out.println("吃苹果");
}
}
class Orange implements Fruit{
@Override
public void eat() {
System.out.println("吃橘子");
}
}
class Factory{
public static Fruit getFruit(String name){
switch(name){
case "Apple":{
return new Apple();
}
case "Orange":{
return new Orange();
}
default : {
return null;
}
}
}
}
public class Test {
public static void main(String[] args) {
Fruit f = Factory.getFruit("Apple");
f.eat();
}
}