TemplateMethod和Strategy模式的区别(实例)

本例取自《敏捷软件开发》地14章,分别使用TemplateMethod和Strategy模式来实现BubbleSort

使用TemplateMethod实现的版本


#include 
using namespace std;

template
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<


void bubbleSorter()
{
	int a[] = {2,1,4,3};

	IntBubbleSorter sorter;
	sorter.sort(a, getLenOfArray(a));
}

实现输出:

1
2
3
4





你可能感兴趣的:(设计模式)