策略模式

定义:将一系列相关算法封装成算法簇,使它们可以相互替换。使算法可以独立于使用者而变换。

适用场景:当类的行为经常发生变化时,可将其行为提取出来,将不同的行为封装成一个算法簇,对使用者只提供一个抽象接口。这样也满足了OO三大原则:封装变化,针对接口编程,多用组合少用继承.

组成:

strategy: 定义所有支持的算法的公共接口

concrete strategy: 实现了具体的算法行为,继承于strategy。

Context :用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用

UML图:



代码:

#include <cstdio>
#include <stack>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <list>
#include <functional>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <string>
#include <map>
#include <iomanip>
#include <cmath>
#include <time.h>
#define LL long long
using namespace std;

// 定义一个武器的接口,英雄可以使用不同的武器,并且可以替换武器
class weapon
{
public:
        virtual void use_weapon()=0;
};

class sword:public weapon
{
public:
        void use_weapon()
        {
                puts("use a sword");
        }
};

class axe:public weapon
{
public:
        void use_weapon()
        {
                puts("use a axe");
        }
};
// 定义使用weapon的hero
class hero
{
private:
        weapon *weap;
public:
        hero(weapon *p):weap(p) {}
        void change_weap(weapon *p)
        {
                delete weap;
                weap = p;
        }
        void attack()
        {
                weap->use_weapon();
        }
};


int main()
{
        hero combatant(new sword);
        combatant.attack();

        combatant.change_weap(new axe);
        combatant.attack();
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值