Design patterns nine (template method pattern)

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Preface

The template method pattern: defines an operation in the skeleton of an algorithm, deferring some steps to subclass. Method lets subclasses can not change the structure of an algorithm redefine certain steps of the algorithm.

Structure diagram

Code to achieve

 AbstractClass is an abstract class, but also is an abstract class, defines and implements a template method, this method is generally a specific method, it gives a top logic framework, which consists of steps of logic in abstract operation corresponding, postponed to subclass implementation. Top logic may also have some concrete method call.

    public abstract class AbstractClass
    {
        public abstract void PrimitiveOperation1();

        public abstract void PrimitiveOperation2();

        public void TemplateMethod()
        {
            PrimitiveOperation1();
            PrimitiveOperation2();
            Console.WriteLine("");
        }
    }

ConcreteClassA, One or more abstract method of the parent class defined. Each AbstractClass can have any corresponding to multiple ConcreteClass, and each ConcreteClass can give the abstract methods (i.e. top logic component steps) different implementation, so that the top logic implementation of each are not identical.

    public class ConCreteClassA : AbstractClass
    {
        public override void PrimitiveOperation1()
        {
            Console.WriteLine("The specific A method 1");
        }

        public override void PrimitiveOperation2()
        {
            Console.WriteLine("The specific A method 2");
        }
    }

    public class ConCreteClassB: AbstractClass
    {
        public override void PrimitiveOperation1()
        {
            Console.WriteLine("The specific B method 1");
        }

        public override void PrimitiveOperation2()
        {
            Console.WriteLine("The specific B method 2");
        }
    }

The client calls

    class Program
    {
        static void Main(string[] args)
        {
            AbstractClass Test;
            Test = new ConCreteClassA();
            Test.TemplateMethod();

            Test = new ConCreteClassB();
            Test.TemplateMethod();

            Console.ReadLine();
        }
    }

 Results are as follows

Summary

 When the constant and variable behavior method in the subclass implementation of mixed together, the same behavior will be repeated in the sub class. We all move to single behavior place through the template method pattern to help get rid of these, entanglement subclass invariant behavior of repeated.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Pauline at November 12, 2013 - 6:15 PM