抽象工厂模式
定义:
抽象工厂模式提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。
ClassDiagram:
图中,是强调CheeseStore的原料Ingredient选择的抽象工厂,四种原料来自南北两方。
PizzaIngredientFactory.h
- #if !defined(_PIZZAINGREDIENTFACTORY_H)
- #define _PIZZAINGREDIENTFACTORY_H
- #include "Dough.h"
- #include "Sauce.h"
- #include "Cheese.h"
- #include "Clam.h"
- class PizzaIngredientFactory
- {
- public:
- virtual Dough* createDough() = 0;
- virtual Sauce* createSauce() = 0;
- virtual Cheese* createCheese() = 0;
- virtual Clam* createClam() = 0;
- };
- #endif //_PIZZAINGREDIENTFACTORY_H
NorthCheesePizzaIngredientFactory.h
- #if !defined(_NORTHCHEESEPIZZAINGREDIENTFACTORY_H)
- #define _NORTHCHEESEPIZZAINGREDIENTFACTORY_H
- #include "PizzaIngredientFactory.h"
- #include "Dough.h"
- #include "Sauce.h"
- #include "Cheese.h"
- #include "Clam.h"
- class NorthCheesePizzaIngredientFactory : public PizzaIngredientFactory
- {
- public:
- Dough* createDough();
- Sauce* createSauce();
- Cheese* createCheese();
- Clam* createClam();
- };
- #endif //_NORTHCHEESEPIZZAINGREDIENTFACTORY_H
Cheese.h
- #if !defined(_CHEESE_H)
- #define _CHEESE_H
- class Cheese
- {
- };
- #endif //_CHEESE_H
NorthCheese.h
- #if !defined(_NORTHCHEESE_H)
- #define _NORTHCHEESE_H
- #include "Cheese.h"
- class NorthCheese : public Cheese
- {
- public:
- NorthCheese();
- };
- #endif //_NORTHCHEESE_H
CheesePizzaStore.h
- #if !defined(_CHEESEPIZZASTORE_H)
- #define _CHEESEPIZZASTORE_H
- #include <string>
- using namespace std;
- class CheesePizzaStore
- {
- public:
- void createPizza(string type);
- };
- #endif //_CHEESEPIZZASTORE_H
CheesePizzaStore.cpp
- #include "stdafx.h"
- #include "CheesePizzaStore.h"
- #include "NorthCheesePizzaIngredientFactory.h"
- #include "SouthCheesePizzaIngredientFactory.h"
- #include "PizzaIngredientFactory.h"
- void CheesePizzaStore::createPizza(string type)
- {
- PizzaIngredientFactory* pf;
- if (type == "North")
- {
- pf = new NorthCheesePizzaIngredientFactory();
- }
- else if(type == "South")
- {
- pf = new SouthCheesePizzaIngredientFactory();
- }
-
- pf->createCheese();
- pf->createClam();
- pf->createDough();
- pf->createSauce();
-
- }
Test.cpp
- #include "stdafx.h"
- #include "CheesePizzaStore.h"
- #include "NorthCheesePizzaIngredientFactory.h"
- #include "SouthCheesePizzaIngredientFactory.h"
- #include "PizzaIngredientFactory.h"
- int main(int argc, char* argv[])
- {
- printf("Hello World!\n");
-
- CheesePizzaStore* cps = new CheesePizzaStore();
- cps->createPizza("North");
- printf("\n----------------------------\n");
- cps->createPizza("South");
- printf("\n");
- return 0;
- }
Output:
- Hello
- NorthCheese.NorthClam.NorthDough.NorthSauce.
- ----------------------------
- SouthCheese.SouthClam.SouthDough.SouthSauce.
- Press any key to continue
完整的项目源码,VC6.0工程。
阅读(852) | 评论(0) | 转发(0) |