/**
* 策略模式: 它定义了算法家族, 分别封装起来,让它们之间可以互相替换,
* 此模式让算法的变化,不会影响到使用算法的客户。
**/
class Strategy
{
public:
virtual void AlgorithmInterface() {};
};
class ConcreteStrategyA : public Strategy
{
public:
virtual void AlgorithmInterface() override
{
cout << "算法1" << endl;
}
};
class ConcreteStrategyB : public Strategy
{
public:
virtual void AlgorithmInterface() override
{
cout << "算法B" << endl;
}
};
class ConcreteStrategyC : public Strategy
{
public:
virtual void AlgorithmInterface() override
{
cout << "算法C" << endl;
}
};
class Context
{
Strategy* m_Strategy;
public:
Context(Strategy* strategy)
{
m_Strategy = strategy;
}
public:
void ContextInterface()
{
m_Strategy->AlgorithmInterface();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Context* _context;
_context = new Context(new ConcreteStrategyA());
_context->ContextInterface();
_context = new Context(new ConcreteStrategyB());
_context->ContextInterface();
_context = new Context(new ConcreteStrategyC());
_context->ContextInterface();
return 0;
}
C++实现 策略模式(0) - 行为型
于 2023-10-26 16:33:00 首次发布