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

本文通过一个具体的C++示例介绍了策略模式的应用。策略模式定义了一系列的算法,并将每一个算法封装起来,使它们可以互相替换。文章展示了如何独立地改变不同子类中的武器行为,并通过接口动态设置角色的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值