c++ 设计模式之策略模式

1 下面是策略模式的类图:


Context(应用场景):

1、需要使用ConcreteStrategy提供的算法。

2、内部维护一个Strategy的实例。

3、负责动态设置运行时Strategy具体的实现算法。

4、负责跟Strategy之间的交互和数据传递。

Strategy(抽象策略类):定义了一个公共接口,各种不同的算法以不同的方式实现这个接口,Context使用这个接口调用不同的算法,一般使用接口或抽象类实现。

ConcreteStrategy(具体策略类):实现了Strategy定义的接口,提供具体的算法实现


2 策略模式就是将算法进行封装,ConcreteStrategyA  ConcreteStrategyB ConcreteStrategyC 是不同的算法,就好像玩CS中武器有AK47的手枪,也有尖刀,用户可以随意使用这两种武器,所以把这个算法封装在Strategy类中。



 3 代码实例:
 

#include<iostream>



using namespace std;

class Weapon   //<span style="font-family: Arial; font-size: 14px; line-height: 26px;">Strategy</span>
{
public: 
	virtual void useWeapon() = 0;
};

class Ak47:public Weapon  //ConcreteStrategyA
{
public:
	void useWeapon()
	{
		cout<<"USE Ak47 to shoot"<<endl;								
	}

};

class Knife:public Weapon  //ConcreteStrategyB
{
public:
	void useWeapon()
	{
		cout<<"USE Knife to kill"<<endl;
	}
};


	 
class Character   //Context
{
public:
	Character()
	{
		m_Weapon = NULL ;
	}

	void setWeapon(Weapon *w)
	{
		m_Weapon = w;
	}

	virtual void fight() =0;

protected:
	Weapon * m_Weapon;
};

class  King:public Character
{
public:
	void fight()
	{
		if(this->m_Weapon == NULL)
		{
			cout<<"You don't have a weapon,Please set weapon!"<<endl;
		}
		else
		{
			m_Weapon->useWeapon();
		}

	}
};

//  下面是主程序代码

// Strategy.cpp : 定义控制台应用程序的入口点。
//
/*策略模式*/
#include "stdafx.h"
#include"Weapon.hpp"

int _tmain(int argc, _TCHAR* argv[])
{
	Weapon *ak47 = new Ak47();
	Weapon *knife = new Knife();
	Character *king = new King();

	king->fight();

	king->setWeapon(ak47);
	king->fight();

	king->setWeapon(knife);
	king->fight();


	system("pause");
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值