Template Method Pattern Code Review

Define the Pattern Interface and Handler Objects

Code Download

Code Review

Code Walkthrough

Define the IPrimitive interface to be used as the "blueprint" for the main application classes.

interface IPrimitive { Int32 CompareTo(Object objectA, Object objectB); }

This interface defines the CompareTo() method. The CompareTo() method represents the generic method to compare two objects.

The PersonPrimitive class (object) defines the CompareTo() method to compare two objects of type Person.

class PersonPrimitive : IPrimitive { public Int32 CompareTo(Object objectA, Object objectB) { Person personA = objectA as Person; Person personB = objectB as Person; Int32 result;
if ((personA == null) || (personB == null)) { throw new InvalidCastException("This object is not of type Person"); } result = personA.Lastname.CompareTo(personB.Lastname);
if (result == 0) { result = personA.Firstname.CompareTo(personB.Firstname); } return (result); } }

The PersonPrimitive class represents the subclass that contains the actual sorting logic.

The CountryPrimitive class (object) defines the CompareTo() method to compare two objects of type String.

class CountryPrimitive : IPrimitive { public Int32 CompareTo(Object objectA, Object objectB) { Country countryA = objectA as Country; Country countryB = objectB as Country; Int32 result;
if ((countryA == null) || (countryB == null)) { throw new InvalidCastException("This object is not of type Country"); } result = countryA.CountryName.CompareTo(countryB.CountryName); return (result); } }

The CountryPrimitive class represents the subclass that contains the actual sorting logic.

The Algorithm class (object) represents the Template Method class containing the CompareTemplateMethod() method.

class Algorithm<T> { private IPrimitive m_primitive;
public Algorithm() { if (this is Algorithm<Person>) { this.m_primitive = new PersonPrimitive(); } if (this is Algorithm<Country>) { this.m_primitive = new CountryPrimitive(); } } public Int32 CompareTemplateMethod(Object objectA, Object objectB) { return(this.m_primitive.CompareTo(objectA, objectB)); } }

The CompareTemplateMethod() invokes the CompareTo() method in the relevant IPrimitive subclass.