《策略模式》

什么是策略模式,用我个人的定义就是利用了面向对象的多态等特性,通过一个类来管理实体类的一种编程技巧。

这种模式在项目中是经常用到的。

 

通过建模大家可以清晰的看到这些类层次关系。下面就用代码来实现一下。

我使用的是VS2005的,大家可以根据需要修改部分代码。

 

[cpp]  view plain copy
  1. #include "stdafx.h"  
  2. #include <iostream>  
  3.   
  4. using namespace  std;  
  5.   
  6. class Strategy  
  7. {  
  8. public:  
  9.     virtual void operate() = 0;  
  10. };  
  11.   
  12.   
  13. class FirstStrategy:public Strategy  
  14. {  
  15.     virtual void operate();  
  16.   
  17. };  
  18.   
  19. void FirstStrategy::operate()  
  20. {  
  21.     cout<<"FirstStrategy::operate()"<<endl;  
  22. }  
  23.   
  24. class SecondStrategy:public Strategy  
  25. {  
  26.     virtual void operate();  
  27.   
  28. };  
  29.   
  30. void SecondStrategy::operate()  
  31. {  
  32.     cout<<"SecondStrategy::operate()"<<endl;  
  33. }  
  34.   
  35. class Context  
  36. {  
  37. public:  
  38.     Context(Strategy* stra);  
  39.     ~Context();  
  40.     void Coperate();  
  41. private:  
  42.     Strategy* m_stra;  
  43. };  
  44.   
  45. Context::Context(Strategy* stra)  
  46. :m_stra(stra)  
  47. {  
  48.   
  49. }  
  50. Context::~Context()  
  51. {  
  52. }  
  53.   
  54. void Context::Coperate()  
  55. {  
  56.     m_stra->operate();  
  57. }  
  58.   
  59.   
  60. int _tmain(int argc, _TCHAR* argv[])  
  61. {  
  62.   
  63.     Strategy* firstStra = new FirstStrategy;  
  64.     Context* context ;  
  65.     context =new Context(firstStra);  
  66.     context->Coperate();  
  67.   
  68.     Strategy* secStra = new SecondStrategy;  
  69.     context =new Context(secStra);  
  70.     context->Coperate();  
  71.       
  72.   
  73.     return 0;  
  74. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值