例如:商场促销手段有打折、返利、积分,都是一些算法。
使用工厂来生成算法对象没有问题,但是这些算法是随时可以互相替换的,这是变化点:
#include<iostream>
#include<memory>
/* 抽象算法类 */
class Strategy {
public:
virtual void AlgorithmInterface() = 0;
virtual ~Strategy() = default;
};
/* 具体算法A */
class ConcreteStrategyA final : public Strategy {
public:
ConcreteStrategyA() = default;
void AlgorithmInterface() override {
std::cout << "algo A implement\n";
}
};
/* 具体算法B */
class ConcreteStrategyB final : public Strategy {
public:
ConcreteStrategyB() = default;
void AlgorithmInterface() override {
std::cout << "algo B implement\n";
}
};
/* 具体算法C */
class ConcreteStrategyC final : public Strategy {
public:
ConcreteStrategyC() = default;
void AlgorithmInterface() override {
std::cout << "algo C implement\n";
}
};
/* 上下文 */
class Context final {
public:
Context() = default;
explicit Context(Strategy* strategy) : strategy_(strategy) {}
Context& operator=(Context&& context) {
strategy_ = std::move(context.strategy_);
return *this;
}
void ContextInterface() {
strategy_->AlgorithmInterface();
}
private:
std::unique_ptr<Strategy> strategy_;
};
auto main(void) -> int {
Context context(new ConcreteStrategyA);
context.ContextInterface();
context = Context(new ConcreteStrategyB);
context.ContextInterface();
context = Context(new ConcreteStrategyC);
context.ContextInterface();
}
策略模式的 Strategy 层次为 Context 定义了一系列可供重用的算法或行为,继承有助于析取出这些算法中的公共部分。