工厂方法模式
定义:定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类把实例化推迟到子类中。
类图:
要点:工厂方法模式能够封装绝提类型的实例化,抽象的Creator提供了一个创建对象的方法的接口,也称“工厂方法”。在抽象的Creator中。任何其他实现的方法,都可能使用到这个工厂方法所制造出来的产品,但只有子类真正实现这个工厂方法并创建产品。工厂方法帮助我们将产品的“实现”与“使用”中解耦。
public abstract class PizzaStore { public Pizza orderPizza(String type){ Pizza pizza; pizza = createPizza(type); pizza.perpare(); pizza.bake(); pizza.box(); pizza.cut(); return pizza; } protected abstract Pizza createPizza(String type); }
public class ChicagoPizzaStore extends PizzaStore{ @Override protected Pizza createPizza(String type) { Pizza pizza = null; if(type.equals("cheese")){ pizza = new ChicagoStyleCheesePizza(); }else if(type.equals("clam")){ pizza = new ChicagoStyleClamPizza(); } return pizza; } }
package hbh.factory; import java.util.ArrayList; public abstract class Pizza { String name; String dough; String sauce; @SuppressWarnings("rawtypes") ArrayList toppings = new ArrayList(); void perpare(){ System.out.println("Preparing " + name); System.out.println("Tossing dough..."); System.out.println("Adding sauce..."); System.out.println("Adding toppings: "); for(int i = 0; i < toppings.size(); i++){ System.out.println(" " + toppings.get(i)); } } void bake(){ System.out.println("Bake for 25 minutse at 350"); } void cut(){ System.out.println("Cutting the pizza into diagonal slices"); } void box(){ System.out.println("Place pizza in offic PizzaStore box"); } public String getName(){ return name; } }
public class ChicagoStyleCheesePizza extends Pizza{ @SuppressWarnings("unchecked") public ChicagoStyleCheesePizza(){ name = "Chicago Style Deep Dish Cheese Pizza"; dough = "Extra Thick Crust Dough"; sauce = "Plum Tomato Sauce"; toppings.add("Shredded Mozzarella Cheese"); } @Override void cut() { System.out.println("Cutting the pizza into square slices"); }
public class ChicagoStyleClamPizza extends Pizza{ @SuppressWarnings("unchecked") public ChicagoStyleClamPizza(){ name = "Chicago Style Deep Dish Clam Pizza"; dough = "Extra Thick Crust Dough"; sauce = "Plum Tomato Sauce"; toppings.add("Shredded Mozzarella Clam"); } @Override void cut() { System.out.println("Cutting the pizza into square slices"); } }
public class PizzaTestDrive { public static void main(String[] args){ // PizzaStore nyStore = new NYPizzaStore(); PizzaStore chicagoStore = new ChicagoPizzaStore(); // Pizza pizza = nyStore.orderPizza("cheese"); // System.out.println("Ethan ordered a " + pizza.getName() + " "); Pizza pizza = chicagoStore.orderPizza("clam"); System.out.println("Joel ordered a " + pizza.getName() + " "); } }
抽象工厂模式
定义:提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。
类图:
要点:通过抽象工厂所提供的接口,可以创建产品的家族,利用这个接口书写代码,我们代码将从实际工厂解耦,以便在不同上下文中实现各式不同的产品。因为代码从实际中解耦了,所以我们可以替换不同的工厂来取得不同的行为。