Skip to content
November 4, 2008 / Shrikant Patil

Behavioral Design Patterns: Template Method Design Pattern

Sometimes we want to specify the order (algorithm) of operations that a method uses, but allow subclasses to provide their own implementations by using the same order (algorithm) of operations. The intension of this pattern is to define an algorithm of operations in a method, and implementation of those operations is defined in subclasses.

Consider the steps of creating any shape on screen;
1.    Accept the shape fill color.
2.    Draw the shape.
3.    Fill specified color.
The above steps define the algorithm to create the shapes. Steps are valid for all types of shapes, either it may circle, rectangle, triangle etc, the same steps needs to be follow.
Coming to the template design pattern, above algorithm of steps are defined in a method called as Template Method in an abstract class, the class also defines the signatures of abstract methods of each steps of algorithms which are get overridden in subclasses to define the specific code.
We will code the application of creating the shapes later; now consider the definition of template method design pattern;
The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

Let’s dig into deep; here is the UML of the pattern;
templatemethodLet us try to understand each part of the pattern;

Abstract Class:
Abstract class defines the templateMethod() signature along with the signatures of methods defined within templateMethod(). Note that the templateMethod() is defined as final, which is important thing of the pattern. If we define any method with final modifier then that method cannot be overridden in its subclasses, this makes a lock on templateMethod’s algorithm. None of its subclasses can change the templateMethod’s procedure.
The templateMethod() defines the sequence of steps, each represented by a method. Abstract class also defines the signatures of methods which are called by templateMethod(). operationA() and operationB() are the methods which are called by the templateMethod(). Class defines the signature of these methods. These methods are overridden in concreteClass to implement the purpose of the method.

ConcreteClass:
A concrete class extends the Abstract Class and overrides the methods to implement the specific code for methods whose signature is defined in Abstract class. The overridden methods called when templateMethod() is called on the Concrete Class

Client:
Client creates the instance of Concrete class and calls its templateMethod().
Let us start creating out shape application; our application can draw two shapes, 1) circle and 2) rectangle.

Creating Abstract Class:
We are creating AbstractShape object as AbstractClass. It contains templateMethod which defines the algorithm of the methods to be called, it accepts a parameter which is used to fill the shape. The templateMethod() calls setShapeColor() and drawShape() methods.
The class also defines the signatures for both setShapeColor() and drawShape() methods. These methods are overridden in subclasses to implement the specific task.


package flexScript
{
    import mx.core.UIComponent;
    //This should be abstract class
    public class AbstractShape extends UIComponent
    {
        //define templateMethod of the class
        public final function templateMethod(color:uint):void
        {
            //define the algorithm of methods
            setShapeColor(color);
            drawShape();
        }
        //define signature of methods called within templateMethod
        protected function setShapeColor(color:uint):void{
            //implemented in subclass
        }
        //define signature of methods called within templateMethod
        protected function drawShape():void{
            //implemented in subclass
        }
    }
}

Creating Concrete Classes:
We are going to create two abstract classes which extends AbstractShape (AbstractClass);
1) CircleShape and
2) RectangleShape, which are used to draw respective shapes whit specified color filled. Both concrete classes override the serShapeColor() and drawShape() methods and implement the respective code for the methods. CircleShape implement the code for drawing the circle and filling it with specified color and RectangleShape class implement the code for drawing the rectangle and filling it with specified color. Note that both implement their own implementation for overridden setShapeColor() and drawShape() methods.
Here is CircleShape class;


package flexScript
{
    //cancrete class extends AbstractClass
    public class CircleShape extends AbstractShape
    {
        //override the methods defined in AbstractClass to implement
        override protected function setShapeColor(color:uint):void{
            this.graphics.beginFill(color);    
        }
        //override the methods defined in AbstractClass to implement
        override protected function drawShape():void{
            this.graphics.drawCircle(0,0,30);
            this.graphics.endFill();
        }
    }
}

And here is RectangleShape Class;


package flexScript
{
    //cancrete class extends AbstractClass
    public class RectangleShape extends AbstractShape
    {
        //override the methods defined in AbstractClass to implement
        override protected function setShapeColor(color:uint):void{
            this.graphics.beginFill(color);
        }
        //override the methods defined in AbstractClass to implement
        override protected function drawShape():void{
            this.graphics.drawRect(0,0,50,50);
            this.graphics.endFill();
        }
    }
}

Creating Client:
In our application, the main MXML file acts as client. It basically contains two checkboxes, through which user can select any one option form both shapes to draw. User can also select the color from colorpicker which can be used to fill the selected shape. Once user clicks on Draw button, init() method is called. The method creates an instance of AbstractShape (AbstractClass), and depending on the user selection for shape to draw, either CircleShape or RectangleShape instance is assigned. Later method calls templateMethod on concreteClass, which results to create a specified shape with selected color filled.
Here is client code.


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute">
<mx:Script>
    <!&#91;CDATA&#91;
    import flexScript.*;

    private function init():void{
        //create instance of AbstractClass
        var a:AbstractShape;
        shapeCanvas.removeAllChildren();
        switch (selectShape.selection.label){
            //create ConcreteInstances
            case "Circle":  a = new CircleShape();
                            break;
            case "Rectangle": a = new RectangleShape();
                            break;
        }
        a.x = (shapeCanvas.width/2) - a.width;
        a.y = (shapeCanvas.height/2)- a.height;
        shapeCanvas.addChild(a);
        //call temlateMethod on ConcreteClass
        a.templateMethod(shapeColor.selectedColor);
        }
    &#93;&#93;>
</mx:Script>
<mx:Canvas x="79" y="45" width="278" height="116">
    <mx:RadioButtonGroup id="selectShape"/>
    <mx:RadioButton label="Circle" y="16" x="25" groupName="selectShape"/>
    <mx:RadioButton label="Rectangle" y="46" x="25" groupName="selectShape"/>
    <mx:Label x="0" y="1" text="Choose Shape to draw"/>
    <mx:Label x="157" y="1" text="Choose color to fill"/>
    <mx:ColorPicker x="164" y="19" id="shapeColor"/>
    <mx:Button x="121" y="74" label="Draw" click="init()"/>
    </mx:Canvas>
    <mx:Canvas x="79" y="169" width="278" height="119" backgroundColor="#FFFFFF"
     id="shapeCanvas">
</mx:Canvas>
</mx:Application>

You need to check this example in flex builder.

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

%d bloggers like this: