策略模式

策略模式作用

在有多种算法相似的情况下,使用 if…else 所带来的复杂和难以维护。策略模式定义了完成相同工作的算法家族,分别封装起来,让他们之间可以相互转换,使算法的改变不会影响使用算法的客户。这样减少了各种算法和使用算法之间的耦合,由于每个算法都有自己的类,通过自己的接口单独测试,简化了单元测试。

UML模型

构建一个基类CashSuper,cash1,cash2继承该基类,context类用来维护对基类及其子类的引用。
在这里插入图片描述

测试代码

#include<iostream>

using namespace std;

class CashSuper
{
public:
	CashSuper() {};
	~CashSuper() {};
	virtual int getvalue() { return 0; };
private:

};

class Cash1:public CashSuper
{
public:
	Cash1(int c) { cash = c; };
	~Cash1() {};
	int getvalue() { return cash; };


private:
	int cash=0;
};

class Cash2 :public CashSuper
{
public:
	Cash2(int c) { cash = c; };
	~Cash2() {};
	int getvalue() { return cash*0.8; };


private:
	int cash = 0;
};



class Context
{
public:
	Context(CashSuper  *CS) { m_CS = CS; };
	~Context() {};
	int GetValue() { return m_CS->getvalue(); };
private:
	CashSuper *m_CS;

};

int main()
{
	Context *context = new Context(new Cash1(10));
	Context *context2 = new Context(new Cash2(10));
	cout << context->GetValue() << endl;
	cout << context2->GetValue() << endl;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

工农村贴膜小哥

我倒是要看看是那个憨憨在给我打

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值