需求:
Pizza 有以下几个方法
prepare() 准备食材
bake() 烘焙
cut() 切割
box() 装盒
现在有2种披萨且和2地区有关,成都地区第一种是CDApplePizza,第二种是CDCheesePizza。北京地区的BJApplePizza和BJApplePizza。
PizzaStore有点单系统Order(city,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+" 开始打包");
}
void setName(String name){
this.pizzaName = name;
}
}
Pizza实现类
public class BJApplePizza extends Pizza {
@Override
public void prepare() {
setName("北京Apple披萨");
System.out.println(pizzaName+" 准备原材料");
}
}
public class BJCheesePizza extends Pizza {
@Override
public void prepare() {
setName("北京Cheese披萨");
System.out.println(pizzaName+" 准备原材料");
}
}
public class CDApplePizza extends Pizza {
@Override
public void prepare() {
setName("成都Apple披萨");
System.out.println(pizzaName+" 准备原材料");
}
}
public class CDCheesePizza extends Pizza {
@Override
public void prepare() {
setName("成都Cheese披萨");
System.out.println(pizzaName+" 准备原材料");
}
}
order抽象类
public abstract class OrderPizza {
String orderType = null;
String city = null;
public OrderPizza(String city,String orderType){
System.out.println("OrderPizza");
this.orderType = orderType;
this.city = city;
Pizza pizza = createPizza();
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
}
abstract Pizza createPizza();
}
order实现类
public class OrderPizzaFactory extends OrderPizza{
public OrderPizzaFactory(String city, String orderType) {
super(city,orderType);
}
@Override
Pizza createPizza( ) {
Pizza pizza;
if (city.equalsIgnoreCase("CD")){
if (orderType.equalsIgnoreCase("cheese")){
pizza = new CDCheesePizza();
}else {
pizza = new CDApplePizza();
}
}else {
if (orderType.equalsIgnoreCase("cheese")){
pizza = new BJCheesePizza();
}else {
pizza = new BJApplePizza();
}
}
return pizza;
}
}
Pizza store
public class PizzaStore {
public static void main(String[] args) {
new OrderPizzaFactory("BJ","cheese");
new OrderPizzaFactory("CD","apple");
}
}
输出结果