策略模式(Strategy)属于行为模式,如果一个事物有多种功能或者是一个功能的多种实现,在不同的场合需要用不同的功能,这种需求就可以用策略模式来实现,首先,这个不同的功能可以通过定义一个公共的接口,然后不同的功能通过实现这个接口来实现,最后功能的调用则可以用一个专门的对象来管理,用以决定具体用那个功能。
熟悉通信的都知道,信号解调需要用到均衡算法,但是均衡算法是多样的,有盲均衡,数据辅助均衡,还有判决反馈均衡等等,在不同的条件下需要用到不用的算法,这样的情形就可以考虑用策略模式来实现。
下面是策略模式的C++实现,代码可到本人github网页下载:设计模式例子
/*
* Example of 'Strategy' design pattern.
* Copyright (C) 2016 Leo Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
using namespace std;
class CStrategy
{
public:
virtual void execute()=0;
};
class CConcreteStrategy1:public CStrategy
{
public:
void execute()
{
cout<<"Special func1!"<<endl;
};
};
class CConcreteStrategy2:public CStrategy
{
public:
void execute()
{
cout<<"Special func2!"<<endl;
};
};
class CContext
{
public:
CStrategy* cp_strategy;
public:
void SetStrategy(CStrategy* p_strategy)
{
cp_strategy=p_strategy;
}
void execute()
{
cp_strategy->execute();
};
public:
CContext(CStrategy* p_strategy)
{
SetStrategy(p_strategy);
};
};
int main()
{
CStrategy* cp_strategy1=new CConcreteStrategy1();
CStrategy* cp_strategy2=new CConcreteStrategy2();
CContext* cp_context=new CContext(cp_strategy1);
cp_context->execute();
cp_context->SetStrategy(cp_strategy2);
cp_context->execute();
return 1;
};