Headfirst设计模式的C++实现——工厂方法(Factory Method)

引用原书的一句话:所有的工厂模式都用来封装对象的创建,工厂方法模式通过让子类决定该创建的对象是什么来达到封装的目的。

Pizza类及其派生类与上一例相同

PizzaStore.h

 #ifndef _PIZZA_STORE_H
#define _PIZZA_STORE_H #include "Pizza.h" class PizzaStore
{
private:
virtual Pizza* CreatePizza(const std::string &type) = ;
public:
Pizza* OrderPizza(const std::string &type)
{
Pizza *p_pizza = CreatePizza(type);
if (p_pizza)
{
p_pizza->prepare();
p_pizza->bake();
p_pizza->cut();
p_pizza->box();
}
return p_pizza;
}
};
#endif

NYPizzaStore.h

 #ifndef _NY_PIZZA_STORE_H
#define _NY_PIZZA_STORE_H #include "PizzaStore.h"
#include "NYCheesePizza.h"
#include "NYGreekPizza.h" class NYPizzaStore : public PizzaStore
{
Pizza* CreatePizza(const std::string &type)
{
if ( "cheese" == type )
{
return new NYCheesePizza();
}
if ( "greek" == type )
{
return new NYGreekPizza();
}
return NULL;
}
};
#endif

ChiChagoPizzaStore.h

 #ifndef _CHICHAGO_PIZZA_STORE_H
#define _CHICHAGO_PIZZA_STORE_H #include "PizzaStore.h"
#include "ChiChagoCheesePizza.h"
#include "ChiChagoGreekPizza.h" class ChiChagoPizzaStore : public PizzaStore
{
Pizza* CreatePizza(const std::string &type)
{
if ( "cheese" == type )
{
return new ChiChagoCheesePizza();
}
if ( "greek" == type )
{
return new ChiChagoGreekPizza();
}
return NULL;
}
};
#endif

main.cpp

 #include "NYPizzaStore.h"
int main()
{
NYPizzaStore pizza_store;
Pizza *p_pizza = pizza_store.OrderPizza("greek");
if ( p_pizza )
{
delete p_pizza;
}
return ;
}
上一篇:第一百七十四节,jQuery,Ajax进阶


下一篇:老男孩Python全栈第2期+课件笔记【高清完整92天整套视频教程】