需求:
Pizza 有以下几个方法
prepare() 准备食材
bake() 烘焙
cut() 切割
box() 装盒
现在有两种披萨,第一种是ApplePizza,第二种是CheesePizza。 PizzaStore有点单系统Order(pizzaType) 根据pizza type去制作对应的Pizza。
Pizza的抽象类
public abstract class Pizza {
String pizzaName = null;
public abstract void prepare();
public void bake(){
System.out.println(pizzaName+" 开始烘焙");
}
public void cut(){
System.out.println(pizzaName+" 开始切割");
}
public void box(){
System.out.println(pizzaName+" 开始打包");
}
}
具体实现类
public class ApplePizza extends Pizza{
@Override
public void prepare() {
System.out.println(pizzaName+" 准备原材料");
}
public ApplePizza(){
pizzaName = "Apple披萨";
}
}
public class CheesePizza extends Pizza{
@Override
public void prepare() {
System.out.println(pizzaName+" 准备原材料");
}
public CheesePizza(){
pizzaName = "Cheese披萨";
}
}
工厂类去实例化Pizza类
public class SimplePizzaFactory {
Pizza pizza=null;
public Pizza createPizzaInstance(String orderType){
if (orderType.equalsIgnoreCase("apple")){
pizza = new ApplePizza();
}else if (orderType.equalsIgnoreCase("cheese")){
pizza = new CheesePizza();
}
return pizza;
}
}
order系统把type传递给工厂类
public class OrderPizza {
public OrderPizza(String orderType){
SimplePizzaFactory simplePizzaFactory = new SimplePizzaFactory();
Pizza pizzaInstance = simplePizzaFactory.createPizzaInstance(orderType);
pizzaInstance.prepare();
pizzaInstance.bake();
pizzaInstance.cut();
pizzaInstance.box();
}
}
披萨店把用户需求传递给order系统
public class PizzaStore {
public static void main(String[] args) {
new OrderPizza("Apple");
new OrderPizza("Cheese");
}
}
输出结果