本文主要是介绍TemplateMethod和Strategy模式的区别(实例),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本例取自《敏捷软件开发》地14章,分别使用TemplateMethod和Strategy模式来实现BubbleSort使用TemplateMethod实现的版本
#include <iostream>
using namespace std;template<typename T>
int getLenOfArray(T& arg)
{return sizeof(arg)/sizeof(arg[0]);
}class BubbleSorter
{
public:virtual ~BubbleSorter(){}protected:int doSort(){if(length<=1){return operations;}for(int nextToLast = length -2; nextToLast >= 0; nextToLast--){for(int index = 0; index <= nextToLast; index++){if(outOfOrder(index)){swap(index);operations++;}}}return operations;}virtual bool outOfOrder(int)=0;virtual void swap(int)=0;protected:int length;private:int operations;
};class IntBubbleSorter:public BubbleSorter
{
public:void sort(int arg[], int size){memcpy(array, arg, size);length = size;doSort();show();}private:bool outOfOrder(int index){return array[index] > array[index + 1];}void swap(int index){int temp = array[index];array[index] = array[index + 1];array[index + 1] = temp;}void show(){for(int index = 0; index < length; index++){cout<<array[index]<<endl;}}private:int array[];
};
void bubbleSorter()
{int a[] = {2,1,4,3};IntBubbleSorter sorter;sorter.sort(a, getLenOfArray(a));
}
实现输出:
1
2
3
4
这篇关于TemplateMethod和Strategy模式的区别(实例)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!