2 工厂模式
1 简单工厂模式
1 具体的需求:披萨的订购:传统的方式实现
1)思路的分析:
2)编写订购的各种需要的代码
① pizza类及其子类的编写
package factory.simplefactory.pizzastore.pizza;
public abstract class Pizza {
protected String name;
//准备原材料,不同得pizza有不同的原材料
public abstract void prepare();
public void bake() {
System.out.println(name+" bakingh;");
}
public void cut() {
System.out.println(name+" cuting;");
}
public void box() {
System.out.println(name+" boxing;");
}
public void setName(String name) {
this.name=name;
}
}
package factory.simplefactory.pizzastore.pizza;
public class GreekPizza extends Pizza{
@Override
public void prepare() {
System.out.println("准备GreekPizza的原材料!");
}
}
package factory.simplefactory.pizzastore.pizza;
public class CheessPizza extends Pizza{
@Override
public void prepare() {
System.out.println("准备cheesspizza的原材料!");
}
}
②order的编写
package factory.simplefactory.pizzastore.order;
import java.util.Scanner;
import factory.simplefactory.pizzastore.pizza.GreekPizza;
import factory.simplefactory.pizzastore.pizza.Pizza;
public class OrderPizza {
public OrderPizza() {
//非简单工厂对象
Pizza pizza=null;
String orderType; //订购pizza的类型’
do {
orderType=getType();
if (orderType.equals("greek")) {
pizza=new GreekPizza();
pizza.setName("希腊");
}else if (orderType.equals("cheess")) {
pizza=new GreekPizza();
pizza.setName("奶酪");
}else {
break;
}
pizza.prepare();
pizza.bake();
pizza.