Template Method Pattern Code Review
Define the Pattern Interface and Handler Objects
Code Download
- Download Description:template method pattern download
- .NET Framework:3.5
- .NET Language:C#
- Date Published:2009-07-01
- Download Size:10 KB
Code Review
- Template Method Pattern Code Review: Define the Pattern Interface and Handler Objects
- Template Method Pattern Code Review: Define the Country and Person Objects
- Template Method Pattern Code Review: Use the Template Method Pattern
Code Walkthrough
Define the IPrimitive interface to be used as the "blueprint" for the main application classes.
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.
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.
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.
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.
Printer Friendly Version
Add to Favourites
DotNet Kicks
Digg
del.icio.us
Live Favourites
ma.gnolia
reddit
Slashdot
Technorati
Yahoo!