策略模式 C++ 实现
2013-06-11 22:38
330 查看
#include<iostream> #include<algorithm> #include<string> /* 问题:和工厂模式的本质区别? */ using namespace std; /*abstract sort class --- strategy class*/ class super_sort { public: typedef int ElemType; void swap(ElemType *a,ElemType*b) { ElemType tmp; tmp=*a; *a=*b; *b=tmp; } virtual void sort(int *a,int l, int r) { } }; /* concrete sort --- concret strategy */ /*quicksort*/ class quick_sort: public super_sort { private: typedef int ElemType; int partition(int *a,int l,int r) {ElemType v=a[r]; int i=l-1;int j=r; while(i<j) { while(a[++i]>v&&i<r) ; while(j>l&&a[--j]<v) ; if(i>=j) break; swap(&a[i],&a[j]); } swap(&a[i],&a[r]); return i; } void quicksort(int *a,int l,int r) { int i; if(l>=r) return; i=partition(a,l,r); quicksort(a,l,i-1); quicksort(a,i+1, r); } public: void sort(int *a, int l, int r) { quicksort(a,l,r); } }; /*insert sort*/ class insert_sort: public super_sort { private: typedef int ElemType; void insertsort(ElemType *a,int l,int r) { int i; for(i=1;i<r;i++) if(a[i]<a[0]) swap(&a[0],&a[i]); for(i=l+2;i<r;i++) { int j=i;ElemType v=a[i]; while(v<a[j-1]) {a[j]=a[j-1];j--;} a[j]=v; } } public: void sort(int *a,int l, int r) { insertsort(a,l,r); } }; /*direct sort*/ class direct_sort: public super_sort { private: void selectsort(int *a,int l,int r) {int i,j; int flag=1; for(i=l;i<r;i++) { int min=i; for(j=i+1;j<10;j++) { if(a[j]<a[min]) min=j; } swap(&a[i],&a[min]); } } public: void sort(int *a, int l, int r) { selectsort(a,l,r); } }; /*context class*/ class context { private: super_sort *my_sort; public: context(){}; void select_sort(int num,int *a, int l, int r) { switch(num) { case 1: my_sort = new quick_sort(); break; case 2: my_sort = new insert_sort(); break; case 3: my_sort = new direct_sort(); break; default: cout << "Erro input, please check. " << endl; } my_sort->sort(a, l, r); } void sort_list() { cout <<"1 -------- quicksort ---------"<< endl; cout <<"2 -------- insertsort ---------"<< endl; cout <<"3 -------- directsort ---------"<< endl; cout << "Input your choice: "<< endl; } }; /* 策略模式 和 简单工厂模式的 区别: 简单工厂模式让客户端识别两个类,而策略模式只让客户端识别一个类; 耦合更加低。 */ /*client class*/ int main() { int num; int a[10] = {1,20,12,0,4,54,22,11,78,8}; context my_selection; my_selection.sort_list(); cin >> num; my_selection.select_sort(num,a,0,9); cout <<"-------- result ---------"<< endl; for(int i = 0; i < 10; i++) cout <<a[i]<< endl; system("pause"); return 0; }
总结:无。
相关文章推荐
- 策略模式C++实现
- 策略模式的C++实现
- 策略模式c++代码实现
- 策略模式c++实现
- 策略模式(2)——c++接口类的实现
- C++ 链表实现构造Huffman树
- 哈夫曼树——C++实现
- scanf/cin输入若干整数以回车结束,并存储,用C/C++实现
- C++实现跨平台游戏开发之Allegro引擎
- matlab2c使用c++实现matlab函数系列教程-harmmean函数
- 堆的c++实现
- C++实现快速排序(源代码)
- [c++]复数类的实现
- unity 调用C++库(android+jni+window dll平台实现)
- C++模板实现归并排序
- matlab2c使用c++实现matlab函数系列教程-ceil函数
- 检查一个二叉树是否平衡的算法分析与C++实现
- 数据结构之循环队列(面向对象思想c++实现)
- 设计模式之适配器模式(C++实现)
- 选择排序-c++代码实现及运行实例结果