标签:family 一个 font int 决定 微软 border void design
简单工厂其实不是一个设计模式,反而像是一种编程习惯,我们来通过它引出工厂设计模式。
先来看一张类图
pizza类
package com.DesignPatterns.ad.factory1; import java.util.ArrayList; abstract public class Pizza { String name; String dough; String sauce; ArrayList<String> toppings = new ArrayList<String>(); public String getName() { return name; } public void prepare() { System.out.println("Preparing " + name); } public void bake() { System.out.println("Baking " + name); | |
} | } public void cut() { System.out.println("Cutting " + name); } public void box() { System.out.println("Boxing " + name); } public String toString() { StringBuffer display = new StringBuffer(); display.append("---- " + name + " ----\n"); display.append(dough + "\n"); display.append(sauce + "\n"); for (String topping : toppings) { display.append(topping + "\n"); } return display.toString(); } |
PizzaStore类
package com.DesignPatterns.ad.factory1;
public class PizzaStore {
SimplePizzaFactory factory;
public PizzaStore(SimplePizzaFactory factory) {
this.factory = factory;
}
public Pizza orderPizza(String type) {
Pizza pizza;
pizza = factory.createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
}
SimplePizzaFactory工厂类
package com.DesignPatterns.ad.factory1; public class SimplePizzaFactory {
public Pizza createPizza(String type) { Pizza pizza = null;
if (type.equals("cheese")) {
pizza = new CheesePizza();
} else if (type.equals("pepperoni")) {
pizza = new PepperoniPizza();
} else if (type.equals("veggie")) {
pizza = new VeggiePizza();
}
return pizza;
}
}
实现类一:CheesePizza
package com.DesignPatterns.ad.factory1;
public class CheesePizza extends Pizza { public CheesePizza() {
name = "Cheese Pizza";
dough = "Regular Crust";
sauce = "Marinara Pizza Sauce";
toppings.add("Fresh Mozzarella");
toppings.add("Parmesan");
}
}
实现类二:PepperoniPizza
package com.DesignPatterns.ad.factory1;
public class PepperoniPizza extends Pizza { public PepperoniPizza() {
name = "Pepperoni Pizza";
dough = "Crust";
sauce = "Marinara sauce";
toppings.add("Sliced Pepperoni");
toppings.add("Sliced Onion");
toppings.add("Grated parmesan cheese");
} | } |
测试类:test
package com.DesignPatterns.ad.factory1;
/**
*
*
*
*
CheesePizza没有的方法,都会去父类里面找的。
*
*
*
*/
public class Test {
public static void main(String[] args) {
SimplePizzaFactory factory = new SimplePizzaFactory();
PizzaStore store = new PizzaStore(factory);
Pizza pizza = store.orderPizza("cheese");
System.out.println("We ordered a " + pizza.getName() + "\n");
System.out.println(pizza);
pizza = store.orderPizza("veggie");
现在假如pizza店是两个点现在改怎么办呢?
标签:family 一个 font int 决定 微软 border void design
原文地址:https://www.cnblogs.com/qingruihappy/p/9739640.html