详解C++设计模式编程中策略模式的优缺点及实现
策略模式(Strategy):它定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法的变化不会影响到使用算法的客户。策略模式和 Template 模式要解决的问题是相同(类似)的,都是为了给业务逻辑(算法)具体实现和抽象接口之间的解耦。策略模式将逻辑(算法)封装到一个类(Context)里面,通过组合的方式将具体算法的实现在组合对象中实现,再通过委托的方式将抽象接口的实现委托给组合对象实现。State 模式也有类似的功能,他们之间的区别将在讨论中给出。 UML图 优点: 实现示例: #include <iostream> #include <string> #include <memory> using namespace std; //strategy抽象类,用作接口 class Strategy { public: virtual string substitute(string str)=0; virtual ~Strategy() { cout<<" in the destructor of Strategy"<<endl; } }; class ChineseStrategy:public Strategy { public: string substitute(string str) { int index=str.find("520"); string tempstr=str.replace(index,3,"我爱你"); return tempstr; } ~ChineseStrategy() { cout<<"in the destructor of ChineseStrategy"<<endl; } }; class EnglishStrategy:public Strategy { public: string substitute(string str) { int index=str.find("520"); string tempstr=str.replace(index,"i love ou"); return tempstr; } ~EnglishStrategy() { cout<<" in the destructor of ChineseStrategy"<<endl; } }; //Context类 class Translator { private: auto_ptr<Strategy> strategy; //在客户代码中加入算法(stategy)类型的指针。 public: ~Translator() { cout<<" in the destructor of Translator"<<endl; } void set_strategy(auto_ptr<Strategy> strategy) { this->strategy=strategy; } string translate(string str) { if(0==strategy.get()) return ""; return strategy->substitute(str); } }; Strategy.cpp #include "Strategy.h" int main(int argc,char *argv) { string str("321520"); Translator *translator=new Translator; //未指定strategy的时候 cout<<"No Strategy"<<endl; translator->translate(str); cout<<"---------------"<<endl; //翻译成中文 auto_ptr<Strategy> s1(new ChineseStrategy); translator->set_strategy(s1); cout<<"Chinese Strategy"<<endl; cout<<translator->translate(str)<<endl; cout<<"---------------"<<endl; //翻译成英文 auto_ptr<Strategy> s2(new EnglishStrategy); translator->set_strategy(s2); cout<<"English Strategy"<<endl; cout<<translator->translate(str)<<endl; cout<<"----------------"<<endl; delete translator; return 0; } 关于策略模式的讨论 可以看到策略模式和 Template 模式解决了类似的问题,也正如在 Template 模式中分析的,策略模式和 Template 模式实际是实现一个抽象接口的两种方式:继承和组合之间的区别。要实现一个抽象接口,继承是一种方式:我们将抽象接口声明在基类中,将具体的实现放在具体子类中。组合(委托)是另外一种方式:我们将接口的实现放在被组合对象中,将抽象接口放在组合类中。这两种方式各有优缺点,先列出来: 从上面对比中我们可以看出,组合相比继承可以取得更好的效果,因此在面向对象的设计中的有一条很重要的原则就是:优先使用(对象)组合,而非(类)继承(FavorComposition Over Inheritance)。 实际上,继承是一种强制性很强的方式,因此也使得基类和具体子类之间的耦合性很强。例如在模板方法模式中在 ConcreteClass1 中定义的原语操作别的类是不能够直接复用(除非你继承自 AbstractClass,具体分析请参看模板方法模式文档)。而组合(委托)的方式则有很小的耦合性,实现(具体实现)和接口(抽象接口)之间的依赖性很小,例如在本实现中,ConcreteStrategyA 的具体实现操作很容易被别的类复用,例如我们要定义另一个 Context 类 AnotherContext,只要组合一个指向策略的指针就可以很容易地复用 ConcreteStrategyA 的实现了。 我们在 桥接模式的问题和桥接模式的分析中,正是说明了继承和组合之间的区别。请参看相应模式解析。 另外策略模式很状态模式也有相似之处,但是状态模式注重的对象在不同的状态下不同的操作。两者之间的区别就是状态模式中具体实现类中有一个指向 Context的引用,而策略模式则没有。具体分析请参看相应的状态模式分析中。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |