菜鸟教程之工厂模式
如下:SteveCode之工厂模式
public class ChinaPizza extends Pizza{ public ChinaPizza() { name = "中国披萨"; size = 12; } @Override void box() { System.out.println("非常之精致的盒子"); } }NyChina
public class NyChina extends Pizza { public NyChina() { name = "牛约披萨"; size = 8; } @Override void cut() { System.out.println("切6片"); } }Pizza
public class Pizza { public String name; public Integer size; void box() { System.out.println("普通包装盒子"); } void cut() { System.out.println("默认切8片"); } public String getName() { return this.name; } }PizzaAbstract
public abstract class PizzaAbstract { public Pizza createPizza(String type) { Pizza pizza = typePizza(type); pizza.box(); pizza.cut(); return pizza; } abstract Pizza typePizza(String type); }TypePizzaFactory
public class TypePizzaFactory extends PizzaAbstract{ @Override Pizza typePizza(String type) { if ("china".equals(type)) { return new ChinaPizza(); } if ("ny".equals(type)) { return new NyChina(); } //不友好测试用 return null; } }测试类:Test
public class Test { public static void main(String[] args) { TypePizzaFactory typePizza = new TypePizzaFactory(); Pizza ny = typePizza.createPizza("ny"); System.out.println("披萨名称="+ny.getName()); Pizza china = typePizza.createPizza("china"); System.out.println("披萨名称="+china.getName()); } }效果图
工厂模式还需要优化
为年薪百万二奋斗终身!给我冲
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)