简单工厂
就是将对象创建的代码从客户程序中解耦出来,单独封装,客户程序中不会出现NEW 新实例.
例子: 一个订PIZZA的例子,PIZZA有很多种比如: CheesePizza、ClamPizza、VeggiePizza等。 通常的实现方法是建立以各PIZZA基类,其他各种PIZZA继承这个类,在PIZZASTORE用到的时候实例化各个类。
这样做的问题就是对象创建的任务交给客户,每出现一种新PIZZA,就要NEW,其实用户只是点PIZZA,其他跟他没关系。
这时候可以采用简单工厂模式,将所有类创建用工厂实现,具体如下:
PIZZA基类:
abstract public class Pizza {
String name;
String dough;
String sauce;
ArrayList toppings = new ArrayList();
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() {
// code to display pizza name and ingredients
StringBuffer display = new StringBuffer();
display.append("---- " + name + " ----\n");
display.append(dough + "\n");
display.append(sauce + "\n");
for (int i = 0; i < toppings.size(); i++) {
display.append((String )toppings.get(i) + "\n");
}
return display.toString();
}
}
具体PIZZA类:
public class CheesePizza extends Pizza {
public CheesePizza() {
name = "Cheese Pizza";
dough = "Regular Crust";
sauce = "Marinara Pizza Sauce";
toppings.add("Fresh Mozzarella");
toppings.add("Parmesan");
}
}
PIZZA工厂类:
public class SimplePizzaFactory {
public Pizza createPizza(String type) {
Pizza pizza = null;
if (type.equals("cheese")) {
pizza = new CheesePizza();
} else //增加其他PIZZA类型
}
return pizza;
}
}
PIZZASTORE类:
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;
}
}
我们看看测试代码:
public class PizzaTestDrive {
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");
;
}
}
只需要告诉需要的PIZZA类型,就可以,完全不用关系怎么实例化该类。
完整代码在本人下载http://down.51cto.com/data/219583 。