标签:tty void 实例 因此 客户 tor 设计方案 print mamicode
//将Pizza 类做成抽象 public abstract class Pizza { protected String name; //名字 //准备原材料, 不同的披萨不一样,因此,我们做成抽象方法 public abstract void prepare(); public void bake() { System.out.println(name + " baking;"); } public void cut() { System.out.println(name + " cutting;"); } //打包 public void box() { System.out.println(name + " boxing;"); } public void setName(String name) { this.name = name; } }
public class BJCheesePizza extends Pizza { @Override public void prepare() { setName("北京的奶酪pizza"); System.out.println(" 北京的奶酪pizza 准备原材料"); } }
public class BJPepperPizza extends Pizza { @Override public void prepare() { setName("北京的胡椒pizza"); System.out.println(" 北京的胡椒pizza 准备原材料"); } }
public class LDCheesePizza extends Pizza{ @Override public void prepare() { setName("伦敦的奶酪pizza"); System.out.println(" 伦敦的奶酪pizza 准备原材料"); } }
public class LDPepperPizza extends Pizza{ @Override public void prepare() { setName("伦敦的胡椒pizza"); System.out.println(" 伦敦的胡椒pizza 准备原材料"); } }
public abstract class OrderPizza { //定义一个抽象方法,createPizza , 让各个工厂子类自己实现 abstract Pizza createPizza(String orderType); // 构造器 public OrderPizza() { Pizza pizza = null; String orderType; // 订购披萨的类型 do { orderType = getType(); pizza = createPizza(orderType); //抽象方法,由工厂子类完成 //输出pizza 制作过程 pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); } while (true); } // 写一个方法,可以获取客户希望订购的披萨种类 private String getType() { try { BufferedReader strin = new BufferedReader(new InputStreamReader(System.in)); System.out.println("input pizza 种类:"); String str = strin.readLine(); return str; } catch (IOException e) { e.printStackTrace(); return ""; } } }
public class BJOrderPizza extends OrderPizza { @Override Pizza createPizza(String orderType) { Pizza pizza = null; if(orderType.equals("cheese")) { pizza = new BJCheesePizza(); } else if (orderType.equals("pepper")) { pizza = new BJPepperPizza(); } return pizza; } }
public class LDOrderPizza extends OrderPizza { @Override Pizza createPizza(String orderType) { Pizza pizza = null; if(orderType.equals("cheese")) { pizza = new LDCheesePizza(); } else if (orderType.equals("pepper")) { pizza = new LDPepperPizza(); } return pizza; } }
public class PizzaStore { public static void main(String[] args) { String loc = "bj"; if (loc.equals("bj")) { //创建北京口味的各种Pizza new BJOrderPizza(); } else { //创建伦敦口味的各种Pizza new LDOrderPizza(); } } }
打印结果:
摘自韩顺平大神笔记
标签:tty void 实例 因此 客户 tor 设计方案 print mamicode
原文地址:https://www.cnblogs.com/liuyi13535496566/p/13287730.html