C++设计模式之策略模式
3608 点击·0 回帖
![]() | ![]() | |
![]() | 写了半天居然异常了,晕死,下面先上代码 1 #include "stdafx.h" 2 #include <iostream> 3 #include "boostshared_ptr.hpp" 4 using namespace std; 5 using namespace boost; 6 7 //--武器类 8 class weapon 9 { 10 public: 11 void virtual attack() = 0; 12 }; 13 14 //--剑 15 class sword:public weapon 16 { 17 public: 18 void attack() 19 { 20 cout<<"using sword to kill 10 enemy per second!"<<endl; 21 } 22 }; 23 24 //--弓箭 25 class archery:public weapon 26 { 27 public: 28 void attack() 29 { 30 cout<<"using archery to kill 10 enemy per second!"<<endl; 31 } 32 }; 33 34 class general 35 { 36 private: 37 weapon *m_strWeapon; 38 string m_strName; 39 shared_ptr<weapon>myWeapon; 40 public: 41 42 43 general(string strName) 44 :m_strName(strName) 45 { 46 myWeapon = shared_ptr<weapon>(new sword); 47 m_strWeapon = myWeapon.get(); 48 } 49 void advance() 50 { 51 cout<<"gogogo!!"<<endl; 52 } 53 void setWeapon(weapon *strWeapon) 54 { 55 m_strWeapon = strWeapon; 56 } 57 58 ~general() 59 { 60 61 62 } 63 64 void performAttack() 65 { 66 m_strWeapon->attack(); 67 } 68 69 }; 70 71 int _tmain(int argc, _TCHAR* argv[]) 72 { 73 //生成卢布对象 74 general LvBu("luBu"); 75 //前进 76 LvBu.advance(); 77 //攻击 78 LvBu.performAttack(); 79 80 shared_ptr<weapon>myWeapon(new archery()); 81 //更换武器 82 LvBu.setWeapon(myWeapon.get()); 83 //前进 www.atcpu.com 84 LvBu.advance(); 85 //攻击 86 LvBu.performAttack(); 87 88 return 0; 89 } 90 91 运行的结果 ![]() 策略模式。重新看一下它的定义:定义一系列的算法,把它们一个个的封装起来,并且使它们可以相互转换。这里所说的一系列的算法封装就是通过继承把各自的实现过程封装到子类中去(我们的例子中是指archery和Sword的实现),而所说的相互转换就是我们通过设置基类指针而只向不同的子类(我们的例子上是通过SetWeapon来实现的)。 实现时需要注意的问题: 1.什么情况下用public继承(is-a),什么情况下用组合(has-a) 2.ocp设计原理(open-close principle) 3.生产对象的释放,shared_ptr的使用和原理。 | |
![]() | ![]() |