策略模式,通过组合的手段将接口进行封装。即,将抽象接口使用于组合类中。
// 策略 抽象类
class Strategy{
public:
virtual void startRun() = 0;
};
class SmartPolicy:public Strategy{
void startRun() override;
};
class SillyPolicy:public Strategy{
void startRun() override;
};
// 组合
class Context{
private:
Strategy *m_pStrategy;
public:
Context(Strategy *org);
void policyRun();
};
void SmartPolicy::startRun()
{
qDebug() << "smart";
}
void SillyPolicy::startRun()
{
qDebug() << "silly";
}
Context::Context(Strategy *org)
{
m_pStrategy = org;
}
void Context::policyRun()
{
m_pStrategy->startRun();
}
Context *pCon = new Context(new SmartPolicy);
pCon->policyRun();