title: 设计模式之简单工厂模式
date: 2019-04-29 20:49:05
tags:
今天下午我们一起订了披萨
public class OrderPizza{
public static void main(String[] args) {
PizzaStore pizzaStore=new PizzaStore(); //大家找了一家披萨店
Pizza pizzaTestA=pizzaStore.produce("CheesePizza"); // A童鞋想吃芝士味
Pizza pizzaTestB=pizzaStore.produce("DurianPizza");// B童鞋想吃榴莲味
Pizza pizzaTestC=pizzaStore.produce("ChinesePizza"); //C同学想吃中国味!!
System.out.println(pizzaTestA.order());
System.out.println(pizzaTestB.order());
System.out.println(pizzaTestC.order());
}
//这就是披萨,它要被我们预定的!!
public interface Pizza {
public String order();
}
//好可惜,从这家看起来店内部看起来好像只有两种口味哎
public class PizzaStore {
public Pizza produce(String pizza) {
if(pizza.equals("CheesePizza")) {
return new CheesePizza();
}
else if(pizza.equals("DurianPizza")) {
return new DurianPizza();
}else {
return new NewPizza();
}
}
}
//这是榴莲的做法
public class DurianPizza implements Pizza{
@Override
public String order() {
return "i order DurianPizza";
}
}
//这是芝士的做法
public class CheesePizza implements Pizza{
@Override
public String order() {
return "i order CheesePizza";
}
}
好了,简单工厂写完了,就好像我们买披萨只需要找披萨店,然后选口味就行。不用去这家找榴莲披萨,那家找芝士披萨,万一跑错门了呢?
如果在优化下,让披萨店提供下菜单,毕竟之前我们点披萨的时候都不知道披萨店有啥子
public class PizzaStore {
public Pizza produceCheesePizza() {
return new CheesePizza();
}
public Pizza produceDurianPizza() {
return new DurianPizza();
}
}
这样大家就不用瞎点了,C同学也不会想出 中国味披萨....
public class OrderPizza{
public static void main(String[] args) {
PizzaStore pizzaStore=new PizzaStore();
Pizza pizzaTestA=pizzaStore.produceCheesePizza();
Pizza pizzaTestB=pizzaStore.produceDurianPizza();
System.out.println(pizzaTestA.order());
System.out.println(pizzaTestB.order());
}
}
所以C童鞋选择吃炒面了
网友评论