策略模式(C++实现)

(本博客旨在个人总结回顾)

1、详情:

策略模式:定义一系列算法,把它们一个个封装起来,使得它们可以相互替换。策略模式使得算法变化可独立于使用它的用户。

说明:

优点: 

①算法可以自由切换。

②避免使用多重条件判断。

③扩展性良好。

缺点:

①策略类会增多。

②所有策略类都需要对外暴露。

2.1、UML类图:

 

2.2、例子源码

stdafx.h

// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

#include <iostream>
using namespace std;

// TODO:  在此处引用程序需要的其他头文件

Strategy.h(策略接口类)

#pragma once

class Strategy
{
public:
    Strategy();
    virtual ~Strategy();

public:
    virtual void Algorithm() = 0;
};

Strategy.cpp

#include "stdafx.h"
#include "Strategy.h"

Strategy::Strategy()
{
}

Strategy::~Strategy()
{
}

StrategyX.h(具体策略类X)

#pragma once
#include "Strategy.h"

class StrategyX :
    public Strategy
{
public:
    StrategyX();
    ~StrategyX();

public:
    void Algorithm();
};

StrategyX.cpp

#include "stdafx.h"
#include "StrategyX.h"

StrategyX::StrategyX()
{
}

StrategyX::~StrategyX()
{
}

void StrategyX::Algorithm()
{
    cout << "算法X实现!" << endl;
}

StrategyY.h(具体策略类Y)

#pragma once
#include "Strategy.h"

class StrategyY :
    public Strategy
{
public:
    StrategyY();
    ~StrategyY();

public:
    void Algorithm();
};

StrategyY.cpp

#include "stdafx.h"
#include "StrategyX.h"

StrategyX::StrategyX()
{
}

StrategyX::~StrategyX()
{
}

void StrategyX::Algorithm()
{
    cout << "算法X实现!" << endl;
}

Context.h

#pragma once
#include "Strategy.h"

class Context
{
public:
    Context(Strategy* pStrategy);
    ~Context();

public:
    void Operation();

private:
    Strategy* m_pStrategy;
};

Context.cpp

#include "stdafx.h"
#include "Context.h"

Context::Context(Strategy* pStrategy)
    : m_pStrategy(pStrategy)
{
}

Context::~Context()
{
    if (m_pStrategy != NULL)
    {
        delete m_pStrategy;
        m_pStrategy = NULL;
    }
}

void Context::Operation()
{
    if (m_pStrategy != NULL)
    {
        m_pStrategy->Algorithm();
    }
}

 

调用代码

StrategyPatternMemo.cpp

// StrategyPatternMemo.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "Context.h"
#include "StrategyX.h"
#include "StrategyY.h"

int _tmain(int argc, _TCHAR* argv[])
{
    Context* pContext = new Context(new StrategyX());
    pContext->Operation();
    delete pContext;

    pContext = new Context(new StrategyY());
    pContext->Operation();
    delete pContext;

    system("pause");
    return 0;
}

2.3、运行结果:

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值