设计模式基础——策略模式
来源:互联网 发布:linux libc 源代码 编辑:程序博客网 时间:2024/06/16 16:22
当类只在某一个算法上存在差异,那么就可以将这部分的算法包装起来,作为类单独的组成部分。而不同的类根据这个部分来区分,并实现不同的操作。
下面是一个例子:
上图中的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 activea->attack();//打印Arrow active return 0;}
0 0
- 设计模式基础——策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式——策略设计模式
- Java设计模式—策略
- 设计模式——策略模式
- 设计模式——策略模式
- 每日设计模式——策略模式
- 印光大师:绮语者,说风流邪僻之话,令人心念淫荡。无知少年听久,必至邪淫以丧人格,或手淫以戕身命
- HDU——1106排序(istringstream的使用、STLvector练习)
- 框架编写之聊天框架认识(一)
- NSDate计算时间差
- JavaScript面向对象原理
- 设计模式基础——策略模式
- 在IntraWeb中使用模板
- C++ 解析Json——jsoncpp
- 梦参老和尚:弘一法师为何听到地藏经第十三品放声大哭
- 图层Layer
- iOS—cell中右边一栏的accessoryView
- 详细记录python的range()函数用法
- Android - JSON Parser Tutorial
- ZOJ-2855-Google Map【4th浙江省赛】