策略模式

本文深入解析策略模式在解决算法变化问题中的应用。策略模式通过定义算法族,将算法封装为独立的对象,允许算法在运行时互换,降低算法与客户端之间的耦合度,简化单元测试。文章提供了一个C++实现的示例,展示了如何通过基类和派生类来实现策略模式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

策略模式作用

在有多种算法相似的情况下,使用 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

工农村贴膜小哥

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

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

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

打赏作者

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

抵扣说明:

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

余额充值