介紹
策略模式將同系列的算法封裝起來,讓使用者可在runtime時替換這些算法。
C++範例
#include <iostream>
class StrategyInterface
{
public:
virtual void Execute() const = 0;
};
class ConcreteStrategyA : public StrategyInterface
{
public:
void Execute() const override
{
std::cout << "Called ConcreteStrategyA execute method" << std::endl;
}
};
class ConcreteStrategyB : public StrategyInterface
{
public:
void Execute() const override
{
std::cout << "Called ConcreteStrategyB execute method" << std::endl;
}
};
class Context
{
public:
explicit Context(StrategyInterface *strategy) : m_strategy(strategy)
{
}
void Setstrategy(StrategyInterface *strategy)
{
m_strategy = strategy;
}
void Execute() const
{
m_strategy->Execute();
}
private:
StrategyInterface *m_strategy;
};
int main(int argc, char *argv[])
{
ConcreteStrategyA concreteStrategyA;
ConcreteStrategyB concreteStrategyB;
// 設定為策略A
Context context(&concreteStrategyA);
// 執行策略A
context.Execute();
// 設定為策略B
context.Setstrategy(&concreteStrategyB);
// 執行策略B
context.Execute();
return 0;
}
Output:
Called ConcreteStrategyA execute method
Called ConcreteStrategyB execute method
Ref:
https://en.wikibooks.org/wiki/C%2B%2B_Programming/Code/Design_Patterns#Strategy