策略(Strategy)模式,是比较简单的一种设计模式,但它的应用却随处可见。下面模拟游戏中常用的打斗场面,来理解策略模式。在游戏中,通常有n个角色,每个角色都能发出动作:fight。每个角色都使用不同的武器,并且可以更换武器。下面是此场景简化的C++实现:
Strategy.h
#ifndef STRETEGY_H
#defineSTRETEGY_H
//定义武器接口
classWeaponBehavior
{
public:
voidvirtualuseWeapon()=0;
};
classSword:publicWeaponBehavior
{
public:
voiduseWeapon();
};
classAxe:publicWeaponBehavior
{
public:
voiduseWeapon();
};
classArrow:publicWeaponBehavior
{
public:
voiduseWeapon();
};
classKnife:publicWeaponBehavior
{
public:
voiduseWeapon();
};
//定义角色接口
classCharacter
{
public:
Character()
{
weapon=0;
}
voidsetWeapon(WeaponBehaviorw)
{
this->weapon=w;
}
voidvirtualfight()=0;
protected:
WeaponBehaviorweapon;
};
classKing:publicCharacter
{
public:
voidfight();
};
classQueen:publicCharacter
{
public:
voidfight();
};
classKnight:publicCharacter
{
public:
voidfight();
};
classTroll:publicCharacter
{
public:
voidfight();
};
#endif
说明:
1.因为每个武器的使用方式不同,所以将使用武器的行为封装成接口,利用此接口调用具体武器的useWeapon行为。
2.因为每个角色都有打斗,更换武器的行为,各个角色的打斗行为不同,而更换武器的行为相同,所以将setWeapon在Character中实现,而打斗行为在各个具体的角色中实现。
Strategy.cpp
#include<iostream>
#include"Strategy.h"
usingnamespacestd;
voidSword::useWeapon()
{
cout<<"Use Sword to stuck!"<<endl;
}
voidAxe::useWeapon()
{
cout<<"Use Axe to chop!"<<endl;
}
voidKnife::useWeapon()
{
cout<<"Use Knife to kill!"<<endl;
}
voidArrow::useWeapon()
{
cout<<"Use arrow!"<<endl;
}
voidKing::fight()
{
cout<<"The king:";
if(this->weapon==NULL)
{
cout<<"You don't have a weapon! Please Set Weapon!"<<endl;
}
else
{
weapon->useWeapon();
}
}
voidQueen::fight()
{
cout<<"The Queen:";
if(this->weapon==NULL)
{
cout<<"You don't have a weapon! Please Set Weapon!"<<endl;
}
else
{
weapon->useWeapon();
}
}
voidKnight::fight()
{
cout<<"The Knight:";
if(this->weapon==NULL)
{
cout<<"You don't have a weapon! Please Set Weapon!"<<endl;
}
else
{
weapon->useWeapon();
}
}
voidTroll::fight()
{
cout<<"The Troll:";
if(this->weapon==NULL)
{
cout<<"You don't have a weapon! Please Set Weapon!"<<endl;
}
else
{
weapon->useWeapon();
}
}
main.cpp
#include<iostream>
#include"Strategy.h"
usingnamespacestd;
intmain()
{
//声明武器
WeaponBehaviorsw=newSword();//声明剑
WeaponBehavioraxe=newAxe();//声明斧头
WeaponBehaviorarr=newArrow();//声明弓箭
WeaponBehaviorkn=newKnife();//声明刀
//声明角色
Characterkin=newKing();
Characterqu=newQueen();
Characterkni=newKnight();
Charactertr=newTroll();
//调用打斗行为
kin->fight();
qu->fight();
kni->fight();
tr->fight();
cout<<endl;
//更换武器
kin->setWeapon(sw);
kin->fight();
cout<<endl;
kin->setWeapon(arr);
kin->fight();
return0;
}
策略(Strategy)模式体现了2个重要的面向对象设计原则:
1.封装变化。
2.针对接口编程。
原文链接: https://www.cnblogs.com/zhangjing0502/archive/2012/06/01/2529446.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/51657
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!