标签:根据 打包 对象 erp 将实例 this color com cto
//将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 interface AbsFactory { //让下面的工厂子类来 具体实现 public Pizza createPizza(String orderType); }
//这是工厂子类 public class BJFactory implements AbsFactory { @Override public Pizza createPizza(String orderType) { System.out.println("~使用的是抽象工厂模式~"); // TODO Auto-generated method stub Pizza pizza = null; if(orderType.equals("cheese")) { pizza = new BJCheesePizza(); } else if (orderType.equals("pepper")){ pizza = new BJPepperPizza(); } return pizza; } }
public class LDFactory implements AbsFactory { @Override public Pizza createPizza(String orderType) { System.out.println("~使用的是抽象工厂模式~"); Pizza pizza = null; if (orderType.equals("cheese")) { pizza = new LDCheesePizza(); } else if (orderType.equals("pepper")) { pizza = new LDPepperPizza(); } return pizza; } }
public class OrderPizza { AbsFactory factory; // 构造器 public OrderPizza(AbsFactory factory) { setFactory(factory); } private void setFactory(AbsFactory factory) { Pizza pizza = null; String orderType = ""; // 用户输入 this.factory = factory; do { orderType = getType(); // factory 可能是北京的工厂子类,也可能是伦敦的工厂子类 pizza = factory.createPizza(orderType); if (pizza != null) { // 订购ok pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); } else { System.out.println("订购失败"); break; } } 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 PizzaStore { public static void main(String[] args) { new OrderPizza(new BJFactory()); //new OrderPizza(new LDFactory()); } }
打印结果:
工厂模式小结
摘自韩顺平大神笔记
标签:根据 打包 对象 erp 将实例 this color com cto
原文地址:https://www.cnblogs.com/liuyi13535496566/p/13287785.html