HEAD_FIRST设计模式学习 ----策略模式 c++简单实现代码
2014-08-14 11:01
816 查看
策略模式定义
定义算法族,分别封装起来,让他们之间可以互相替换,此模式让算法变化独异于使用算法的客户。
下面是根据书上的鸭子应用简单的c++实现代码
这是模仿三国使用策略
定义算法族,分别封装起来,让他们之间可以互相替换,此模式让算法变化独异于使用算法的客户。
下面是根据书上的鸭子应用简单的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; }
相关文章推荐
- First head 设计模式学习c++实现------模板方法模式(Template method pattern)
- 简单了解设计模式中的装饰者模式及C++版代码实现
- 设计模式学习笔记一 简单工厂策略模式实现销售策略的变更(一)
- (2)--策略模式【设计模式C++实现】
- 设计模式:策略模式的实现 c++ 与 java
- 设计模式系列1-----C++实现策略模式(Strategy)
- 设计模式之C++实现(二)---策略模式(Strategy)
- 设计模式 -- 简单工厂模式 -- c++实现
- 设计模式C++实现(2)——策略模式
- 设计模式之简单工厂模式:c++实现
- .NET Romoting 学习总结(三)—— Remoting技术之设计模式实现代码安全
- (C++)设计模式------单例模式 singleton(简单的实现和对象释放的控制) -- 创建型模式
- Head First 设计模式 C++实现-Strategy(策略模式)
- 学习设计模式之结合简单工厂,策略,装饰的计算器
- 学习php设计模式 php实现策略模式(strategy)
- C++设计模式 --单例模式(简单的实现和对象释放的控制)
- 设计模式学习笔记以及java代码实现
- state设计模式学习, 一个C++的实现
- 设计模式 -- 策略模式 -- c++实现
- Head-first设计模式(一)——策略模式(Strategy Pattern)