设计模式:抽象工厂
Pizza
public abstract class Pizza { // 披萨名称 private String pizzaName; /** * 披萨准备工作 */ public abstract void prepare(); public void bake() { System.out.println(pizzaName + "正在烘烤"); } public void cut() { System.out.println(pizzaName + "正在剪切"); } public void pack() { System.out.println(pizzaName + "正在打包"); } public void setPizzaName(String pizzaName) { this.pizzaName = pizzaName; } }
BJCheesePizza
public class BJCheesePizza extends Pizza{ @Override public void prepare() { setPizzaName("北京奶酪披萨"); System.out.println("北京奶酪披萨正在准备中"); } }
BJPepperPizza
public class BJPepperPizza extends Pizza { @Override public void prepare() { setPizzaName("北京胡椒披萨"); System.out.println("北京胡椒披萨正在准备中"); } }
LDCheesePizza
public class LDCheesePizza extends Pizza { @Override public void prepare() { setPizzaName("伦敦奶酪披萨"); System.out.println("伦敦奶酪披萨正在准备中"); } }
LDPepperPizza
public class LDPepperPizza extends Pizza{ @Override public void prepare() { setPizzaName("伦敦胡椒披萨"); System.out.println("伦敦胡椒披萨正在准备中"); } }
AbsFactory
public interface AbsFactory { /** * 创建pizza * @param pizzaType 披萨类型 * @return 需要创建的pizza */ Pizza createPizza(String pizzaType); }
BJFactory
public class BJFactory implements AbsFactory{ @Override public Pizza createPizza(String pizzaType) { if ("cheese".equals(pizzaType)) { return new BJCheesePizza(); } else if ("pepper".equals(pizzaType)) { return new BJPepperPizza(); } return null; } }
LDFactory
public class LDFactory implements AbsFactory { @Override public Pizza createPizza(String pizzaType) { if ("cheese".equals(pizzaType)) { return new LDCheesePizza(); } else if ("pepper".equals(pizzaType)) { return new LDCheesePizza(); } return null; } }
OrderPizza
public class OrderPizza { public OrderPizza(AbsFactory factory) { handlerPizza(factory); } private void handlerPizza(AbsFactory factory) { do { String pizzaType = getPizzaType(); Pizza pizza = factory.createPizza(pizzaType); if (Objects.nonNull(pizza)) { pizza.prepare(); pizza.bake(); pizza.cut(); pizza.pack(); } else { System.out.println("输入的pizza目前不支持制作,请等待"); break; } } while (true); } /** * 获取要制作的pizza * * @return pizza种类 */ private String getPizzaType() { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print("请输入要订购的披萨:"); String pizzaType = reader.readLine(); System.out.println("要订阅的pizza种类:" + pizzaType); return pizzaType; } catch (IOException e) { e.printStackTrace(); return ""; } } }
PizzaStore
public class PizzaStore { public static void main(String[] args) { // new OrderPizza(new LDFactory()); new OrderPizza(new BJFactory()); } }