interface IFood {
void getFood();
}
class Bread implements IFood {
@Override
public void getFood() {
System.out.println("eat break");
}
}
class Milk implements IFood {
@Override
public void getFood() {
System.out.println("eat milk");
}
}
class Factory {
public static IFood getInstance(String className) {
if (className.equals("break")) {
return new Bread();
} else if (className.equals("milk")) {
return new Milk();
} else {
return null;
}
}
}
public class FactoryDemo {
public static void main(String[] args) {
IFood food = Factory.getInstance(args[0]);
food.getFood();
}
}
运行结果:
- javac FactoryDemo.java
- java FactoryDemo break
eat break
说明: 程序运行与IFood接口没有任何关联,所有的关联都是通过Factory完成。后续需要扩充,只需要在Factory中添加就可以了。