Wzorzec jest przykładem klasycznego rozwiązania w zakresie wielokrotnego wykorzystania gotowego kodu w świecie programowania obiektowego. Uniwersalne algorytmy są umieszczane w klasach bazowych będących przedmiotem dziedziczenia. W klasach dziedziczących natomiast implementowane są wymagane metody i wykorzystywany jest algorytm zaimplementowany w klasie bazowej.
public abstract class BubbleSorter
{
private int operations = 0;
protected int length = 0;
protected int DoSort()
{
operations = 0;
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;
}
protected abstract void Swap(int index);
protected abstract bool OutOfOrder(int index);
}
public class IntBubbleSorter : BubbleSorter
{
private int[] array = null;
public int Sort(int[] theArray)
{
array = theArray;
length = array.Length;
return DoSort();
}
protected override void Swap(int index)
{
int temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
}
protected override bool OutOfOrder(int index)
{
return (array[index] > array[index + 1]);
}
}