https://github.com/zytc2009/BigTeam_learning
分类:
2011-04-18 22:40:12
#ifndef _STRETEGY_H_
#define _STRETEGY_H_
//定义武器接口
class WeaponBehavior

{
public:
void virtual useWeapon() = 0;
};
class Sword:public WeaponBehavior

{
public:
void useWeapon();
};
class Axe:public WeaponBehavior

{
public:
void useWeapon();
};
class Arrow:public WeaponBehavior

{
public:
void useWeapon();
};
class Knife:public WeaponBehavior

{
public:
void useWeapon();
};
//定义角色接口
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();
};
class Queen:public Character

{
public:
void fight();
};
class Knight:public Character

{
public:
void fight();
};
class Troll:public Character

{
public:
void fight();
};

#endif
#include <iostream>
#include "Strategy.h"
using namespace std;
void Sword::useWeapon()

{
cout << "Use Sword to stuck!" << endl;
}
void Axe::useWeapon()

{
cout << "Use Axe to chop!" << endl;
}
void Knife::useWeapon()

{
cout << "Use Knife to kill!" << endl;
}
void Arrow::useWeapon()

{
cout << "Use arrow!" << endl;
}
void King::fight()

{
cout << "The king:" ;
if ( this->weapon == NULL)
{
cout << "You don't have a weapon! Please Set Weapon!" << endl;
}
else
{
weapon->useWeapon();
}
}
void Queen::fight()

{
cout << "The Queen:" ;
if ( this->weapon == NULL)
{
cout << "You don't have a weapon! Please Set Weapon!" << endl;
}
else
{
weapon->useWeapon();
}
}
void Knight::fight()

{
cout << "The Knight:" ;
if ( this->weapon == NULL)
{
cout << "You don't have a weapon! Please Set Weapon!" << endl;
}
else
{
weapon->useWeapon();
}
}
void Troll::fight()

{
cout << "The Troll:";
if ( this->weapon == NULL)
{
cout << "You don't have a weapon! Please Set Weapon!" << endl;
}
else
{
weapon->useWeapon();
}
}
#include <iostream>
#include "Strategy.h"
using namespace std;
int main()

{
//声明武器
WeaponBehavior *sw = new Sword();//声明剑
WeaponBehavior *axe = new Axe();//声明斧头
WeaponBehavior *arr = new Arrow();//声明弓箭
WeaponBehavior *kn = new Knife();//声明刀
//声明角色
Character *kin = new King();
Character *qu = new Queen();
Character *kni = new Knight();
Character *tr = new Troll();
//调用打斗行为
kin->fight();
qu->fight();
kni->fight();
tr->fight();
cout << endl;
//更换武器
kin->setWeapon(sw);
kin->fight();
cout << endl;
kin->setWeapon(arr);
kin->fight();
return 0;
}