说明
当类只在某一个算法上存在差异,那么就可以将这部分的算法包装起来,作为类单独的组成部分。而不同的类根据这个部分来区分,并实现不同的操作。
下面是一个例子:
上图中的Character是一个父类,根据使用不同的武器,又分为Warrior和Archer两个子类。这里就使用到了策略模式,Weapon被包装成了一个类,根据不同的武器,攻击的时候会有不同的效果,而效果包装在Weapon中,并有active方法实现。
下面是具体的代码:
1. 武器的实现:
/************************ Weapon *****************************/
class Weapon {
public:
virtual void active();
};
void Weapon::active() {
cout << "Weapon active" << endl;
}
/************************ Sword *****************************/
class Sword : public Weapon {
void active() override;
};
void Sword::active() {
cout << "Sword active" << endl;
}
/************************ Arrow *****************************/
class Arrow : public Weapon {
void active() override;
};
void Arrow::active() {
cout << "Arrow active" << endl;
}
2. 人物的实现:
/************************ Character *****************************/
class Character {
private:
Weapon *weapon;
public:
void setWeapon(Weapon *weapon);
void attack();
};
void Character::setWeapon(Weapon *weapon) {
this->weapon = weapon;
}
void Character::attack() {
weapon->active();
}
/************************ Warrior *****************************/
class Warrior : public Character{
//本例中不需要特别实现什么
};
/************************ Archer *****************************/
class Archer : public Character {
//本例中不需要特别实现什么
};
3. 测试:
int main()
{
Warrior *w = new Warrior();
Sword *s = new Sword();
w->setWeapon(s);
Archer *a = new Archer();
Arrow *ar = new Arrow();
a->setWeapon(ar);
w->attack(); //打印Sword active
a->attack(); //打印Arrow active
return 0;
}