Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1414957
  • 博文数量: 241
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 2253
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-11 22:27
个人简介

--

文章分类

全部博文(241)

文章存档

2021年(3)

2019年(6)

2018年(1)

2017年(9)

2016年(21)

2015年(50)

2014年(125)

2013年(26)

我的朋友

分类: C/C++

2014-02-25 13:31:24

1、是什么?
    定义算法家族,分别封装起来,让他们之间互相替换,此模式让算法变化,但不会让使用者收到影响。

2、为什么?何时?
    定义一系列算法,所有这些算法完成相同的工作,只是实现不同,采用相同的方式调用所有算法,减少了各种算法类与使用算法类之间的耦合。同样可以使用简单工厂模式实现。

3、如何做?UML类图


4、示例代码

点击(此处)折叠或打开

  1. #include <iostream>
  2. using namespace std;

  3. class CashSuper
  4. {
  5. public:
  6.     virtual double acceptCash() = 0;
  7. };
  8. class CashNormal : public CashSuper
  9. {
  10. public:
  11.     double acceptCash()
  12.     {
  13.         cout<<"正常收费"<<endl;
  14.         return 0;
  15.     }
  16. };
  17. class CashDiscount : public CashSuper
  18. {
  19. public:
  20.     double acceptCash()
  21.     {
  22.         cout<<"折扣收费"<<endl;
  23.         return 0;    
  24.     }
  25. };
  26. class CashContent
  27. {
  28. public:
  29.     CashContent(CashSuper* c)
  30.     {
  31.         cash = c;
  32.     }
  33.     double getResult()
  34.     {
  35.         cash->acceptCash();
  36.         return 0;
  37.     }
  38. private:
  39.     CashSuper* cash;
  40. };
  41. void main()
  42. {
  43.     cout<<"hello \n";
  44.     CashSuper* cash;
  45.     int type;
  46.     cin>>type;
  47.     switch(type)
  48.     {
  49.     case 0:
  50.             cash = new CashNormal();
  51.             break;
  52.     case 1:
  53.             cash = new CashDiscount();
  54.             break;
  55.     default:
  56.             cash = new CashNormal();
  57.             break;
  58.     }
  59.     CashContent* content = new CashContent(cash);
  60.     content->getResult();
  61. }
阅读(888) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~