C++设计模式之策略模式(Strategy)
生活随笔
收集整理的這篇文章主要介紹了
C++设计模式之策略模式(Strategy)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Strategy策略模式
作用:定義了算法家族,分別封裝起來,讓他們之間可以互相替換,此模式讓算法的變化,不會(huì)影響到使用算法的客戶。
UML圖:
代碼實(shí)現(xiàn)
#include <iostream> using namespace std;class Strategy { public:~Strategy() {}virtual void AlgrithmInterface() = 0; protected:Strategy() {} };class ConcreteStrategyA : public Strategy { public:ConcreteStrategyA() {}~ConcreteStrategyA() {}virtual void AlgrithmInterface() { cout << "ConcreteStrategyA::AlgrithmInterface" << endl; } };class ConcreteStrategyB : public Strategy { public:ConcreteStrategyB() {}~ConcreteStrategyB() {}virtual void AlgrithmInterface() { cout << "ConcreteStrategyB::AlgrithmInterface" << endl; } };/*這個(gè)類是Strategy模式的關(guān)鍵,也是Strategy模式和Template模式的根本區(qū)別所在。*Strategy通過“組合”(委托)方式實(shí)現(xiàn)算法(實(shí)現(xiàn))的異構(gòu),而Template模式則采取的是繼承的方式這兩個(gè)模式的區(qū)別也是繼承和組合兩種實(shí)現(xiàn)接口重用的方式的區(qū)別 */ class Context { public:Context(Strategy* strategy) { this->_strategy = strategy; }~Context() { delete this->_strategy; }void DoAction() { this->_strategy->AlgrithmInterface(); } private:Strategy* _strategy; };int main() {/*Strategy模式和Template模式實(shí)際是實(shí)現(xiàn)一個(gè)抽象接口的兩種方式:繼承和組合之間的區(qū)別。要實(shí)現(xiàn)一個(gè)抽象接口,繼承是一種方式:我們將抽象接口聲明在基類中,將具體的實(shí)現(xiàn)放在具體子類中。組合(委托)是另外一種方式:我們將接口的實(shí)現(xiàn)放在被組合對象中,將抽象接口放在組合類中。這兩種方式各有優(yōu)缺點(diǎn)*/Strategy* pStr = new ConcreteStrategyA(); //策略A與B可替換Context* pcon = new Context(pStr);pcon->DoAction();pStr = new ConcreteStrategyB();pcon = new Context(pStr);pcon->DoAction();return 0; }輸出結(jié)果:
參考資料
1.??C++設(shè)計(jì)模式-Strategy策略模式
總結(jié)
以上是生活随笔為你收集整理的C++设计模式之策略模式(Strategy)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: lol卡萨丁的大招范围
- 下一篇: LOL无双剑姬怎么操作啊