Strategy.h
#ifndef _STRATEGY_H_
#define _STRATEGY_H_
class CStrategy
{
public:
CStrategy();
virtual~CStrategy();
virtual void AlgrithmInterface()=0;
};
class CConcreteStrategyA:public CStrategy
{
public:
CConcreteStrategyA();
~CConcreteStrategyA();
void AlgrithmInterface();
};
class CConcreteStrategyB:public CStrategy
{
public:
CConcreteStrategyB();
~CConcreteStrategyB();
void AlgrithmInterface();
};
class CContext
{
public:
CContext(CStrategy *_str);
~CContext();
void ContextAlgrithmInterface();
private:
CStrategy *_str;
};
#endif
Strategy.cpp
#include <iostream>
#include "Strategy.h"
using namespace std;
CStrategy::CStrategy()
{
}
CStrategy::~CStrategy()
{
}
CConcreteStrategyA::CConcreteStrategyA()
{
}
CConcreteStrategyA::~CConcreteStrategyA()
{
}
void CConcreteStrategyA::AlgrithmInterface()
{
cout<<"CConcreteStrategyA"<<endl;
}
CConcreteStrategyB::CConcreteStrategyB()
{
}
CConcreteStrategyB::~CConcreteStrategyB()
{
}
void CConcreteStrategyB::AlgrithmInterface()
{
cout<<"CConcreteStrategyB"<<endl;
}
CContext::CContext(CStrategy *_str)
{
this->_str=_str;
}
CContext::~CContext()
{
if(_str)
{
delete _str;
_str=0;
}
}void CContext::ContextAlgrithmInterface(){if(_str)_str->AlgrithmInterface();}
Main.cpp
#include <iostream>
#include "Strategy.h"
using namespace std;
int main() //Client
{
CStrategy *_str=new CConcreteStrategyA;
CContext *_con=new CContext(_str);
_con->ContextAlgrithmInterface();
if(_str)
{
delete _str;
_str=0;
}
if(_con)
{
delete _con;
_con=0;
}
return 0;
}
Strategy模式和Template模式要解决的问题是相同(类似)的,都是为了给业务逻辑(算法)具体实现和抽象接口之间的解耦。Strategy模式将逻辑(算法)封装到一个类(Context)里面,通过组合的方式将具体算法的实现在组合对象中实现,再通过委托的方式将抽象接口的实现委托给组合对象实现
Main.cpp
#include <iostream>
#include "Strategy.h"
using namespace std;
int main() //Client
{
CStrategy *_str=new CConcreteStrategyA;
CContext *_con=new CContext(_str);
_con->ContextAlgrithmInterface();
if(_str)
{
delete _str;
_str=0;
}
if(_con)
{
delete _con;
_con=0;
}
return 0;
}
Strategy模式和Template模式要解决的问题是相同(类似)的,都是为了给业务逻辑(算法)具体实现和抽象接口之间的解耦。Strategy模式将逻辑(算法)封装到一个类(Context)里面,通过组合的方式将具体算法的实现在组合对象中实现,再通过委托的方式将抽象接口的实现委托给组合对象实现
标签:CConcreteStrategyA,CContext,Strategy,CStrategy,str,设计模式,con
From: https://blog.51cto.com/u_13566975/7272471