深入解析C++编程中对设计模式中的策略模式的运用

2020-01-06 14:43:02于丽
易采站长站为您分析C++编程中对设计模式中的策略模式的运用,需要的朋友可以参考下  

策略模式也是一种非常常用的设计模式,而且也不复杂。下面我们就来看看这种模式。
定义:策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。

角色:

  •     抽象策略角色(Strategy): 抽象策略类。
  •     具体策略角色(ConcreteStrategy):封装了继续相关的算法和行为。
  •     环境角色(Context):持有一个策略类的引用,最终给客户端调用。

    UML图:

     

    C++编程,设计模式,策略模式

     

    例子:

    
    #include <iostream> 
    using namespace std; 
     
    class WeaponBehavior 
    { 
    public: 
      void virtual useWeapon() = 0; 
    }; 
     
    class AK47:public WeaponBehavior 
    { 
    public: 
      void useWeapon() 
      { 
        cout << "Use AK47 to shoot!" << endl; 
      } 
    }; 
     
    class Knife:public WeaponBehavior 
    { 
    public: 
      void useWeapon() 
      { 
        cout << "Use Knife to kill!" << endl; 
      } 
    }; 
     
    class Character 
    { 
    public: 
      Character() 
      { 
        weapon = 0; 
      } 
      void setWeapon(WeaponBehavior *w) 
      { 
        this->weapon = w; 
      } 
      void virtual fight() = 0; 
    protected: 
      WeaponBehavior *weapon; 
    }; 
     
    class King:public Character 
    { 
    public: 
      void fight() 
      { 
        cout << "The king:" ; 
        if ( this->weapon == NULL) 
        { 
          cout << "You don't have a weapon! Please Set Weapon!" << endl; 
        } 
        else 
        {  
          weapon->useWeapon(); 
        } 
      } 
    }; 
    int main() 
    {   
      WeaponBehavior *ak47 = new AK47(); 
      WeaponBehavior *knife = new Knife();    
     
      Character *kin = new King();    
     
      kin->fight();   
      cout << endl;  
     
      kin->setWeapon(ak47); 
      kin->fight(); 
      cout << endl; 
     
      kin->setWeapon(knife); 
      kin->fight(); 
     
      return 0; 
    }