【设计模式】策略模式

说明

当类只在某一个算法上存在差异,那么就可以将这部分的算法包装起来,作为类单独的组成部分。而不同的类根据这个部分来区分,并实现不同的操作。

下面是一个例子:

上图中的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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值