Design Pattern, kick start... Article I - Strategy Pattern

来源:互联网 发布:重装系统后没网络 编辑:程序博客网 时间:2024/06/08 15:47

  Oh, it was so long time from I decided to study design pattern. But so far, I had little konwlege about it, since it was so hard to me to keep enthusiasm, sigh... Today, I made up my mind to study it again. To record the whole process and share with all people, I am planning to write my experience here. Hope it useful to help me keep going. ^_^

/* Sample for Strategy Pattern
This pattern defines a family of algorighms, encapsulates each one, and makes them interchangeable.
In sample below, you can independently change each weapon behavior in each subClass. Also you can dynamically set a charater's (or subClass) behavior by interface provided. Moreover, you can reuse the exsited code as much as possible. It's very loose-coupling. */


#include <iostream>

using namespace std;

class WeaponBehavior
{
public:
 WeaponBehavior(){}
 virtual void useWeapon()
 {
  cout << "WeaponBehavior" << endl;
 }
};
class KnifeBehavior : public WeaponBehavior
{
public:
 void useWeapon()
 {
  cout << "KnifeBehavior" << endl;
 }
};

class AxeBehavior : public WeaponBehavior
{
public:
 void useWeapon()
 {
  cout << "AxeBehavior" << endl;
 }
};

class BowAndArrowBehavior : public WeaponBehavior
{
public:
 void useWeapon()
 {
  cout << "BowAndArrowBehavior" << endl;
 }
};

class SwordBehavior : public WeaponBehavior
{
public:
 void useWeapon()
 {
  cout << "SwordBehavior" << endl;
 }
};

class Character
{
public:
 Character()
 {
  myWeaponBehavior = new WeaponBehavior();
 }
 virtual void fight()
 {
  myWeaponBehavior->useWeapon();
 }
 void setWeaponBehavior(WeaponBehavior* w)
 {
  myWeaponBehavior = w;
 }
protected:
 WeaponBehavior* myWeaponBehavior;
};

class Queen : public Character
{
public:
 Queen()
 {
  myWeaponBehavior = new AxeBehavior();
 }
};

class King : public Character
{
public:
 King()
 {
  myWeaponBehavior = new SwordBehavior();
 }
};

class Troll : public Character
{
public:
 Troll()
 {
  myWeaponBehavior = new BowAndArrowBehavior();
 }
};

class Knight : public Character
{
public:
 Knight()
 {
  myWeaponBehavior = new KnifeBehavior();
 }
};

 int main (int argc, char *argv[])
{
 Queen* myQueen = new Queen();
 myQueen->fight();
 King* myKing = new King();

 myKing->fight();
 myKing->setWeaponBehavior(new KnifeBehavior());
 myKing->fight();
 return(0);
}

Enjoy!