Design patterns in C# – part 15 (Template Method pattern)

Role

The Template Method pattern enables algorithms to defer certain steps to subclasses.

Design

TemplateMethodPattern

Implementation

using System;

namespace TemplateMethodPattern
{
    public class TestTemplateMethodPattern
    {
        public static void Main(string[] args)
        {
            var algorithm = new Algorithm();

            algorithm.TemplateMethod(new MyClass());
            algorithm.TemplateMethod(new OtherClass());
        }
    }

    public interface IPrimitives
    {
        string Name { get; }
        string DisplayInfo();
    }

    public class Algorithm
    {
        public void TemplateMethod(IPrimitives primitives)
        {
            Console.WriteLine(String.Format("Class - {0} \tmessage: {1}", primitives.Name, primitives.DisplayInfo()));
        }
    }

    public class MyClass : IPrimitives
    {
        #region IPrimitives Members

        public string DisplayInfo()
        {
            return "My own class !";
        }

        public string Name
        {
            get { return GetType().Name; }
        }

        #endregion
    }

    public class OtherClass : IPrimitives
    {
        #region IPrimitives Members

        public string DisplayInfo()
        {
            return "Other class !";
        }

        public string Name
        {
            get { return GetType().Name; }
        }

        #endregion
    }
}

OUTPUT:

Class – MyClass         message: My own class !
Class – OtherClass      message: Other class !

Use when

  • Common behavior can be factored out of an algorithm.
  • The behavior varies according to the type of a subclass.

Bibliography

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s