您的位置:首页 > 编程语言 > C语言/C++

HEAD_FIRST设计模式学习 ----策略模式 c++简单实现代码

2014-08-14 11:01 816 查看
策略模式定义

定义算法族,分别封装起来,让他们之间可以互相替换,此模式让算法变化独异于使用算法的客户。

下面是根据书上的鸭子应用简单的c++实现代码

#include <iostream>
using namespace std;

class DuckInterface
{
public:
virtual void fly()=0;
};
class flyA:public DuckInterface
{
public:
void fly()
{
cout<<"低飞"<<endl;
}
};
class flyB:public DuckInterface
{
public:
void fly()
{
cout<<"高飞"<<endl;
}
};
class Duck
{
public:
Duck(DuckInterface *duckFly)
{
this->duckFly = duckFly;
}
~Duck()
{
if(duckFly) delete duckFly;
}
void fly()
{

this->duckFly->fly();
}
private:
DuckInterface *duckFly;
};

int main()
{
Duck  a(new flyA);
a.fly();
Duck b(new flyB);
b.fly();
}


这是模仿三国使用策略

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
//策略接口
class StrategyInterface
{
public:
StrategyInterface(){}
virtual ~StrategyInterface(){}
virtual void GetStrategy() = 0;
};

class Strategy
{
public:
Strategy(string name ,StrategyInterface *strategy)
{
this->username = name;
this->strategy = strategy;
}

~Strategy()
{
if (strategy)
{
delete strategy;
}
}

void UseStrategy()
{
cout << username + "使用了";
strategy->GetStrategy();
}

private:
string username;
StrategyInterface *strategy;
};

class FirstStrategy:public StrategyInterface
{
void GetStrategy()
{
cout << "第一个策略" << endl;
}

};

class SecondStrategy :public StrategyInterface
{
void GetStrategy()
{
cout << "第二条策略" << endl;
}
};

int main()
{
Strategy *zhaoyun = new Strategy("赵云", new FirstStrategy());
Strategy *zhangfei = new Strategy("张飞", new SecondStrategy());
zhaoyun->UseStrategy();
zhangfei->UseStrategy();
delete zhaoyun,zhangfei;
return 0;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: