1、优缺点
1.1、优点
相较于简单定义各算法,将各算法组织起来并进行了一定的封装,方便了不同算法之间的切换。
笔者感受:
使用类C操控类A继承体系A1,A2,A3中公有对外暴露接口。
利用一个额外的类,(1)将strategy抽象策略基类,作为额外类的入参;
(2)将strategy抽象策略基类作为额外类的成员变量,利用多态原理,接收外面传来的具体抽象策略。
(3)对外暴露的接口中,使用成员变量抽象策略基类,调用策略继承体系中的子类们都需要继承的纯虚函数接口。
即可,使用额外类操控策略继承体系中公有对外暴露的接口了。
1.2、缺点
将算法类暴露给了用户,用户依然得直接依赖具体子算法。
1.3、优化
见 《大话设计模式》C++实现:02 策略模式(四)——(策略模式+简单工厂)
2、代码
2.1、结果
main.cpp
#include "Strategy.h"
#include "Context.h"
void test()
{
Context* pContext = nullptr;
/* StrategyA */
pContext = new Context(new StrategyA());
pContext->contextInterface();
/* StrategyB */
pContext = new Context(new StrategyB());
pContext->contextInterface();
/* StrategyC */
pContext = new Context(new StrategyC());
pContext->contextInterface();
delete pContext;
pContext = nullptr;
}
int main()
{
test();
system("pause");
}
2.2、代码
2.2.1、Strategy.h
#pragma once
#include <iostream>
using namespace std;
/*
策略模式:定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的用户。
*/
/* 抽象策略基类:定义所有支持算法的公共接口 */
class Strategy
{
public:
virtual void algorithmInterface() = 0;
};
/* 策略A */
class StrategyA :public Strategy
{
public:
virtual void algorithmInterface()override
{
cout << "算法A实现" << endl;
}
};
/* 策略B */
class StrategyB :public Strategy
{
public:
virtual void algorithmInterface()override
{
cout << "算法B实现" << endl;
}
};
/* 策略C */
class StrategyC :public Strategy
{
public:
virtual void algorithmInterface()override
{
cout << "算法C实现" << endl;
}
};
2.2.2、Context.h
#pragma once
#include "Strategy.h"
/*
笔者感受:使用类C操控类A继承体系A1,A2,A3中公有对外暴露接口。
利用一个额外的类,(1)将strategy抽象策略基类,作为额外类的入参;
(2)将strategy抽象策略基类作为额外类的成员变量,利用多态原理,接收外面传来的具体抽象策略。
(3)对外暴露的接口中,使用成员变量抽象策略基类,调用策略继承体系中的子类们都需要继承的纯虚函数接口。
即可,使用额外类操控策略继承体系中公有对外暴露的接口了。
*/
class Context
{
public:
Context(Strategy* pStrategy) :m_pStrategy(pStrategy) {}
void contextInterface();
private:
Strategy* m_pStrategy{ nullptr };
};
void Context::contextInterface()
{
m_pStrategy->algorithmInterface();
}
此为《大话设计模式》学习心得系列 P23~~