策略模式
2011-11-24 16:16
141 查看
策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用算法,减少了各种算法类与使用算法类之间的耦合。
// Strategy.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class IStrategy
{
public:
virtual void algorithmInterface()= 0;
};
class StrategyA: public IStrategy
{
void algorithmInterface()
{
cout<< "Strategy A algorithmInterface"<<endl;
}
};
class StrategyB: public IStrategy
{
void algorithmInterface()
{
cout<<"Strategy B algorithmInterface"<<endl;
}
};
class StrategyContext
{
public:
void setStrategy( IStrategy *stragety)
{
myStrategy = stragety;
}
void executeStrategy()
{
myStrategy->algorithmInterface();
}
private:
IStrategy *myStrategy;
};
int _tmain(int argc, _TCHAR* argv[])
{
StrategyContext context;
StrategyA * stragetyA = new StrategyA();
context.setStrategy( stragetyA );
context.executeStrategy();
delete stragetyA;
StrategyB * stragetyB = new StrategyB();
context.setStrategy( stragetyB );
context.executeStrategy();
delete stragetyB;
system("pause");
return 0;
}
// Strategy.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class IStrategy
{
public:
virtual void algorithmInterface()= 0;
};
class StrategyA: public IStrategy
{
void algorithmInterface()
{
cout<< "Strategy A algorithmInterface"<<endl;
}
};
class StrategyB: public IStrategy
{
void algorithmInterface()
{
cout<<"Strategy B algorithmInterface"<<endl;
}
};
class StrategyContext
{
public:
void setStrategy( IStrategy *stragety)
{
myStrategy = stragety;
}
void executeStrategy()
{
myStrategy->algorithmInterface();
}
private:
IStrategy *myStrategy;
};
int _tmain(int argc, _TCHAR* argv[])
{
StrategyContext context;
StrategyA * stragetyA = new StrategyA();
context.setStrategy( stragetyA );
context.executeStrategy();
delete stragetyA;
StrategyB * stragetyB = new StrategyB();
context.setStrategy( stragetyB );
context.executeStrategy();
delete stragetyB;
system("pause");
return 0;
}
相关文章推荐
- (12)策略模式
- 设计模式学习(一)——策略模式
- 策略模式(headfirst设计模式学习笔记)
- 【Unity3D与23种设计模式】策略模式(Strategy)
- 设计模式(策略模式)
- 设计模式--策略模式
- 策略模式
- java策略模式
- 23种设计模式之行为型模式——策略模式
- 从“假如有下面几种价格10,20,50,请你代码实现将他们排序输出”看设计模式中的策略模式
- Android SDK开发 -- TitleBar重构 - 使用策略模式、舍弃代理模式
- 策略模式
- JavaScript设计模式之策略模式实例
- 策略模式
- Java 实现策略(Strategy)模式
- PHP设计模式实例之(观察者模式、策略模式、简单工厂模式)
- head first设计模式(一)——策略模式
- .NET策略(Strategy)模式
- 我设计的策略模式(Strategy)
- 设计模式之工厂模式和策略模式