Chinaunix首页 | 论坛 | 博客
  • 博客访问: 167068
  • 博文数量: 71
  • 博客积分: 165
  • 博客等级: 入伍新兵
  • 技术积分: 431
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-17 00:35
文章分类
文章存档

2013年(3)

2012年(68)

分类:

2012-11-09 13:22:01

factory.h

点击(此处)折叠或打开

  1. #ifndef _FACTORY_H_
  2. #define _FACTORY_H_

  3. class Human
  4. {
  5. public:
  6.     virtual void laguage() = 0;
  7. };


  8. class WhiteHuman : public Human
  9. {
  10. public:
  11.     void laguage();
  12. };

  13. class BlackHuman : public Human
  14. {
  15. public:
  16.     void laguage();
  17. };

  18. class YellowHuman : public Human
  19. {
  20. public:
  21.     void laguage();
  22. };

  23. class Factory
  24. {
  25. public:
  26.     Factory()
  27.     {
  28.     }
  29.     ~Factory()
  30.     {
  31.     }
  32. public:
  33.     static Human * getHum(Human * hu);
  34. private:
  35.     static Human * hum; /// < 不是静态的getHum不能直接调用;原因...
  36. };

  37. #endif
factory.c

点击(此处)折叠或打开

  1. #include "factory.h"
  2. #include <iostream>
  3. using namespace std;

  4. void WhiteHuman::laguage()
  5. {
  6.     cout << "我说英语" << endl;
  7. }

  8. void BlackHuman::laguage()
  9. {
  10.     cout << "我说外语" << endl;
  11. }

  12. void YellowHuman::laguage()
  13. {
  14.     cout << "我说汉语" << endl;
  15. }

  16. Human * Factory::hum = NULL;

  17. Human * Factory::getHum(Human * hu)
  18. {
  19.     if (NULL == hu)
  20.         return NULL;
  21.     hum = hu;
  22.     
  23.     return hum;
  24. }
main.c

点击(此处)折叠或打开

  1. #include "factory.h"

  2. int main(int argc, const char *argv[])
  3. {
  4.     Human * white = Factory::getHum(new WhiteHuman());
  5.     white->laguage();
  6.     delete white;

  7.     Human * black = Factory::getHum(new BlackHuman());
  8.     black->laguage();
  9.     delete black;

  10.     Human * yellow = Factory::getHum(new YellowHuman());
  11.     yellow->laguage();
  12.     delete yellow;

  13.     return 0;
  14. }

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