倚楼听风雨,淡看江湖路

朝花夕拾

2011年8月15日

设计模式-策略模式

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

posted @ 2011-08-15 14:27 小闵 阅读(1373) | 评论 (1)编辑 收藏

仅列出标题  
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿

随笔分类

随笔档案

搜索

最新评论