策略模式
定义
策略模式封装了算法族,分别封装起来,让它们之间可以互换,此模式让算法变化独立于使用算法的客户。
类图
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| class Character { protected: WeaponBehavior* weapon; public: virtual void fight() { weapon->useWeapon(); }
void setWeapon(WeaponBehavior* w) { weapon = w; } };
class King : public Character { public: King() { weapon = new SwordBehavior(); } };
class Queen : public Character { public: Queen() { weapon = new BowAndArrowBehavior(); } };
class Knight : public Character { public: Knight() { weapon = new AxeBehavior(); } };
class Troll : public Character { public: Troll() { weapon = new KnifeBehavior(); } };
class WeaponBehavior { public: virtual void useWeapon() = 0; };
class SwordBehavior : public WeaponBehavior { public: void useWeapon() { cout << "Using sword!!!" << endl; } };
class BowAndArrowBehavior : public WeaponBehavior { public: void useWeapon() { cout << "Using bow and arrow!!!" << endl; } };
class AxeBehavior : public WeaponBehavior { public: void useWeapon() { cout << "Using axe!!!" << endl; } };
class KnifeBehavior : public WeaponBehavior { public: void useWeapon() { cout << "Using knife!!!" << endl; } };
|
理解
把客户的行为抽象成一个接口,具体的行为继承这个接口并实现出自己特定的行为,客户不需要和具体的行为打交道,只需要和接口打交道,减少耦合,而且利于扩展,只需要扩展特定行为,不需要对客户代码做改变。