设计模式之策略模式

策略模式(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;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值