设计模式-行为-Strategy(策略)模式

本文介绍了软件设计中的策略模式,通过具体的代码示例展示了如何使用该模式来实现算法的解耦和灵活替换。策略模式允许在运行时选择合适的算法,提高了系统的可扩展性和维护性。

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

和Template一样的目的,只不过实现手法是组合 而不是Template模式的继承,解决了继承所带来的弊端。

问题:

    为了给业务逻辑(算法)具体的实现和抽象的接口之间的解耦。

    把算法 (业务逻辑)封装到一个Contex类中通过组合的方式,实现在组合对象中,通过委托的方式将抽象接口的实现委托给组合对象的实现State模式也有类似区别

    定义了一些列的算法,并且封装起来,使他们可以相互替换,策略模式让算法独立于客户的变化而独立变化

171235_mpOg_1391394.jpg


#include "PublicHeaders.h"

class Strategy
{
public:
	virtual void AlgrithmInterface() = 0;
};

class ConCreateStrategy :public Strategy
{
public:
	void AlgrithmInterface()override
	{
		cout << __FUNCTION__ << endl;
	}

};
class Contex
{
public:
	Contex(Strategy *strategy)
	{
		this->strategy = strategy;
	}

	void DoAction()
	{
		this->strategy->AlgrithmInterface();
	}
private:
	Strategy*strategy;
};


/**
 * @brief  test function for strategy pattern
 */
void testStrategy()
{
	Contex* contex = new Contex(new ConCreateStrategy);

	contex->DoAction();

}




例2

武器系统

class WeaponStrategy
	{
	public:
		virtual void doFire() = 0;
	};

	class GaTlingGun_Strategy :public WeaponStrategy
	{
	public:
		virtual void doFire()override
		{


		}

	};

	class PistolGun_Strategy :public WeaponStrategy
	{
	public:
		virtual void doFire()override
		{

		}

	};


	class PlayerContex
	{
	public:
		void Fire()
		{
			weapon->doFire();
		}


		void setWeapon(WeaponStrategy *strategy)
		{
			this->weapon = strategy;
		}

		WeaponStrategy*weapon;
	};

	void test()
	{
		PlayerContex*player = new PlayerContex;
		player->setWeapon(new GaTlingGun_Strategy);

		player->Fire();


	}


转载于:https://my.oschina.net/kkkkkkkkkkkkk/blog/669178

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值