Wednesday, April 7, 2010

Template Design Pattern By Example in C#

This is part of a series of posts in which we will deal with some of the popular design patters using simple but non-trivial examples.

Template Design Pattern is a very simple design pattern and yet is very useful.  It helps in situations where multiple tasks have common functionality but have some distinct variations.

Lets dive straight into our example. The download link to this sample is available at the bottom. Our task here is to import data into our system from multiple sources.  The task of  checking for duplication and adding to our repository is common functionality.  Whereas reading and converting the incoming data to our format would be different for each kind of datasource.  In our example we need to import Xml and CSV data into our repository.

Template Pattern involves creating a abstract class with common functionality implemented and defines abstract methods and properties for areas which are variable.

So lets check out the actors in our example:
  • ImportData Abstract Class - implements common functionality like checking for duplicate data and inserting into our repository.  But only defines abstract methods for initialising the incoming data and converting the incoming data into a common format.
  • ImportCSVData Class - inherits from ImportData abstract class and implements the required property and methods.  This class adds functionality to import from CSV data.

  • ImportXmlData Class - likewise inherits from ImportData and adds functionality to import from XML data.
Thus if in the future, we are required to import yet another type of data we would create another class inheriting from the abstract base class and implementing it.

Download Sample Code

Happy Coding