Headfirst设计模式的C++实现——工厂方法(Factory Method)
引用原书的一句话:所有的工厂模式都用来封装对象的创建,工厂方法模式通过让子类决定该创建的对象是什么来达到封装的目的。
Pizza类及其派生类与上一例相同
PizzaStore.h
1 #ifndef _PIZZA_STORE_H 2 #define _PIZZA_STORE_H 3 4 #include "Pizza.h" 5 6 class PizzaStore 7 { 8 private: 9 virtual Pizza* CreatePizza(const std::string &type) = 0; 10 public: 11 Pizza* OrderPizza(const std::string &type) 12 { 13 Pizza *p_pizza = CreatePizza(type); 14 if (p_pizza) 15 { 16 p_pizza->prepare(); 17 p_pizza->bake(); 18 p_pizza->cut(); 19 p_pizza->box(); 20 } 21 return p_pizza; 22 } 23 }; 24 #endif
NYPizzaStore.h
1 #ifndef _NY_PIZZA_STORE_H 2 #define _NY_PIZZA_STORE_H 3 4 #include "PizzaStore.h" 5 #include "NYCheesePizza.h" 6 #include "NYGreekPizza.h" 7 8 class NYPizzaStore : public PizzaStore 9 { 10 Pizza* CreatePizza(const std::string &type) 11 { 12 if ( "cheese" == type ) 13 { 14 return new NYCheesePizza(); 15 } 16 if ( "greek" == type ) 17 { 18 return new NYGreekPizza(); 19 } 20 return NULL; 21 } 22 }; 23 #endif
ChiChagoPizzaStore.h
1 #ifndef _CHICHAGO_PIZZA_STORE_H 2 #define _CHICHAGO_PIZZA_STORE_H 3 4 #include "PizzaStore.h" 5 #include "ChiChagoCheesePizza.h" 6 #include "ChiChagoGreekPizza.h" 7 8 class ChiChagoPizzaStore : public PizzaStore 9 { 10 Pizza* CreatePizza(const std::string &type) 11 { 12 if ( "cheese" == type ) 13 { 14 return new ChiChagoCheesePizza(); 15 } 16 if ( "greek" == type ) 17 { 18 return new ChiChagoGreekPizza(); 19 } 20 return NULL; 21 } 22 }; 23 #endif
main.cpp
1 #include "NYPizzaStore.h" 2 int main() 3 { 4 NYPizzaStore pizza_store; 5 Pizza *p_pizza = pizza_store.OrderPizza("greek"); 6 if ( p_pizza ) 7 { 8 delete p_pizza; 9 } 10 return 0; 11 }