本例取自《敏捷软件开发》地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