策略模式
#include<iostream> using namespace std; //基类,接口 class SortBase { public: SortBase(){}; virtual void datasort(){}; }; // QuickSort 子类 class QuickSort:public SortBase { public: void datasort(); }; void QuickSort::datasort() { cout<<"This is QuickSort!"<<endl; }; // BubbleSort 子类 class BubbleSort:public SortBase { public: void datasort(); }; void BubbleSort::datasort() { cout<<"This is BubbleSort!"<<endl; }; //应用场景 class SortContext { private: SortBase *sort; public: SortContext(SortBase *_sort); void doSort(); }; SortContext::SortContext( SortBase *_sort) { this->sort=_sort; } void SortContext::doSort() { sort->datasort(); }; //主函数 int main() { string sortmodel; while(1){ cin>>sortmodel; SortContext *sortcontext=new SortContext(new BubbleSort() ); sortcontext->doSort(); sortcontext=new SortContext(new QuickSort() ); sortcontext->doSort(); } return 0; }
策略模式,定义一系列算法,把它们封装起来,并且它们之间可以相互替换。
以下情况下考虑使用该模式。
1.许多相关的类仅仅是行为不同。
2.需要使用一个算法的不同变体。
3.算法使用客户不应该知道的数据。
4.一个类定义了多种行为,并且行为在类中以条件语句的形式出现。