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

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

文章分类
文章存档

2013年(4)

2012年(10)

我的朋友

分类: C/C++

2012-07-29 16:02:16

简单工厂模式
 
今天学习一个简单的模式,简单工厂模式。对于这个模式,还是有些争论的,但不是针对它的内容以及使用,而是说它属不属于设计模式范畴,当然我从不关心这个,只要好用我拿来用就是了。
 
OK,继续。
 
定义:
    简单工厂模式,把对象的产生过程封装成一个类,这个类就是工厂类,客户需要对象时,向工厂索取就可以了。
 
下面一个例子,生产Pizza过程,当客户到PizzaStore买Pizza时,只需要告诉想要的type就可以了。
 
ClassDiagram:
PizzaStore.h
  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. };

  11. #endif //_PIZZASTORE_H
SimplePizzaFactory.h
  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. };

  11. #endif //_PIZZASTORE_H
Pizza.h
  1. #if !defined(_PIZZA_H)
  2. #define _PIZZA_H


  3. class Pizza
  4. {
  5. public:
  6.     virtual void prepare();
  7.     virtual void bake();
  8.     virtual void cut();
  9.     virtual 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
ClamPizza.h
  1. #if !defined(_CLAMPIZZA_H)
  2. #define _CLAMPIZZA_H

  3. #include "Pizza.h"

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

  9. #endif //_CLAMPIZZA_H
Output:

  1. Hello World!
  2. Cheese Pizza prepare bake cut box.
  3. Clam Pizza prepare bake cut box.
  4. Press any key to continue


完整的工程代码,VC6.0.




 
阅读(692) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~