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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章