// strategy.cpp : 定義控制臺應用程序的入口點。
//
#include "stdafx.h"
/********************************************************************
created: 2011/08/15
created: 15:8:2011 10:37
file base: strategy
file ext: cpp
author: lost boy
purpose: 設計模式-策略模式
策略模式是指定義一系列的算法,把它們一個個封裝起來,并且使它們可相互替換。
本模式使得算法可獨立于使用它的客戶而變化。也就是說這些算法所完成的功能一樣,
對外的接口一樣,只是各自實現上存在差異。用策略模式來封裝算法,效果比較好。
*********************************************************************/
/*
電腦戰術
*/
class BotsTactics
{
public:
virtual void DoTactics() = 0;
};
/*
吹風流
*/
class TacticsBlown : public BotsTactics
{
public:
void DoTactics()
{
printf("bot use Blown tactics\n");
}
};
/*
熊流
*/
class TacticsBears : public BotsTactics
{
public:
void DoTactics()
{
printf("bot use Bears tactics\n");
}
};
/*
塔流
*/
class TacticsTowerRush : public BotsTactics
{
public:
void DoTactics()
{
printf("bot use TowerRush tactics\n");
}
};
/*
也是直接通過參數指定,只不過不是傳入指針,而是一個標簽。
用戶只需要知道標簽
*/
enum TATICS {BLOWN, BEAR, TR}; //標簽
class Bots
{
private:
BotsTactics *pTatics_;
public:
Bots(enum TATICS ta)
{
if (ta == BLOWN)
pTatics_ = new TacticsBlown;
else if(ta == BEAR)
pTatics_ = new TacticsBears;
else if (ta == TR)
pTatics_ = new TacticsTowerRush;
else
pTatics_ = NULL;
}
~Bots()
{
if (pTatics_)
{
delete pTatics_;
pTatics_ = NULL;
}
};
public:
void DoTactics()
{
pTatics_->DoTactics();
}
};
/*
利用模板實現。算法通過模板的實參指定。
*/
template<class ta>
class templateBots
{
private:
ta ta_;
public:
templateBots(){}
~templateBots(){}
public:
void DoTactics()
{
ta_.DoTactics();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Bots bot(BLOWN);
bot.DoTactics();
templateBots<TacticsTowerRush> bot1;
bot1.DoTactics();
return 0;
}