Chinaunix首页 | 论坛 | 博客
  • 博客访问: 46867
  • 博文数量: 14
  • 博客积分: 297
  • 博客等级: 二等列兵
  • 技术积分: 547
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-08 21:05
个人简介

努力做自己不喜欢的事情!

文章分类
文章存档

2013年(4)

2012年(10)

我的朋友

分类: C/C++

2012-07-29 20:21:21

工厂方法模式
 
定义:
    工厂方法模式定义了一个创建对象的接口,但由子类决定实例化具体哪一个类。工厂方法将类的实例化推迟到子类。
 
ClassDiagram:
 
    当客户像PizzaStore要CheesePizza时(call orderPizza()),orderPizza会调用具体子类实现的CheesePizzaStore.createPizza(),这样具体创建Pizza对象的操作就延迟到了工厂的子类。
 
PizzaStore.sh
  1. #if !defined(_PIZZASTORE_H)
  2. #define _PIZZASTORE_H

  3. #include "Pizza.h"
  4. #include <string>
  5. using namespace std;
  6. class PizzaStore
  7. {
  8. public:
  9.     Pizza* orderPizza(string type);
  10.     virtual Pizza* createPizza(string type) = 0;
  11. };

  12. #endif //_PIZZASTORE_H

CheesePizzaStore.h
  1. #if !defined(_CHEESEPIZZASTORE_H)
  2. #define _CHEESEPIZZASTORE_H

  3. #include "PizzaStore.h"

  4. class CheesePizzaStore : public PizzaStore
  5. {
  6. public:
  7.     Pizza* createPizza(string type);
  8. };

  9. #endif //_CHEESEPIZZASTORE_H
Pizza.h
  1. #if !defined(_PIZZA_H)
  2. #define _PIZZA_H


  3. class Pizza
  4. {
  5. public:
  6.     void prepare();
  7.     void bake();
  8.     void cut();
  9.     void box();
  10. };

  11. #endif //_PIZZA_H
CheesePizza.h

  1. #if !defined(_CHEESEPIZZA_H)
  2. #define _CHEESEPIZZA_H

  3. #include "Pizza.h"

  4. class CheesePizza : public Pizza
  5. {
  6. public:
  7.     CheesePizza();
  8. };

  9. #endif //_CHEESEPIZZA_H

Test.cpp
  1. #include "stdafx.h"
  2. #include "PizzaStore.h"
  3. #include "CheesePizzaStore.h"
  4. #include "ClamPizzaStore.h"
  5. int main(int argc, char* argv[])
  6. {
  7.     printf("Hello World!\n");
  8.     PizzaStore* ps = new CheesePizzaStore();
  9.     ps->orderPizza("Cheese");

  10.     PizzaStore* ps2 = new ClamPizzaStore();
  11.     ps2->orderPizza("Clam");
  12.     return 0;
  13. }
Output:
  1. Hello World!
  2. Cheese Pizza prepare bake cut box.
  3. Clam Pizza prepare bake cut box.
  4. Press any key to continue

    相对来说,简单工厂、工厂方法都是比较理解的设计模式,也是很实用的模式,它对象的生成与使用相分离,也就是解耦合,我们想用对象,从工厂获取就可以。
    本节重点是,相较简单方法,工厂方法中工厂(PizzaStore)提供抽象工厂方法(createPizza()),由子类来实现,已达到创建Pizza对象后移到工厂子类。
 
 
完整的项目代码,VC6.0工程。
 
 
阅读(803) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~