Template Method

 Rate It (4)

Template Method

The Template Method is know as a behavioral pattern which lets subclasses implement behaviour that can vary. In the example below we use the Template Method to allow sub classes to implement how a hot drink is made.

A VB example of the Temple Method Pattern

Public Class MyPage
     
     Public Sub Page_Load()
     
        
Dim CupOfTea As HotDrink
        CupOfTea =
New Tea

       
Dim CupOfCoffee As HotDrink
        CupOfCoffee =
New Coffee

        Ma
keDrink(CupOfTea)        

        Response.write(
".........<br/>")

        MakeDrink(CupOfCoffee)

     End Sub

     ''' <summary>
     
''' Generic Method that will make the hot Drink
     
''' </summary>
    
Public Sub MakeDrink(ByVal HotDrink As HotDrink)
      
        HotDrink.boilWater()
        HotDrink.addIngredients()
        HotDrink.addCondiments()
    
End Sub
End Class

''' <summary>
''' Abstract Class
'''
</summary>
Public MustInherit Class HotDrink

     Public Sub boilWater()
          Response.write(
"Boiling Water...<br/>")
    
End Sub

     Public MustOverride Sub addIngredients()

     Public MustOverride Sub addCondiments()
End Class

''' <summary>
''' Tea Class that implements behaviour that can vary i.e.
''' the addIngredients & addCondiments methods
'''
</summary>
Public Class Tea
    
Inherits HotDrink

     Public Overrides Sub addCondiments()
         Response.write(
"Add Milk ...<br/>")
    
End Sub

     Public Overrides Sub addIngredients()
         Response.write(
"Add Tea Bags ...<br/>")
    
End Sub
End Class

''' <summary>
''' Coffee Class that implements behaviour that can vary i.e.
''' the addIngredients & addCondiments methods
'''
</summary>
Public Class Coffee
    
Inherits HotDrink

     Public Overrides Sub addCondiments()
         Response.write(
"Add Milk ...<br/>")
    
End Sub

     Public Overrides Sub addIngredients()
         Response.write(
"Add Coffee Granules ...<br/>")
    
End Sub

End Class

UML

Template Method UML

Revision number 2, Tuesday, June 24, 2008 8:22:27 PM by scott@elbandit.co.uk

Comments

Hi, Good example. You can read about the pattern in more details and get a C# example in the following post I wrote: http://blogs.microsoft.co.il/blogs/gilf/archive/2008/06/13/template-method-pattern.aspx

Related Articles

Design Patterns

Design Patterns Design patterns are recognized solutions to common problems defined originally by the Gang of Four programmers. Design patterns are used throughout the ASP.NET Framework. The various patterns are commonly divided into several different groups

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. mbanavige (5)
  2. SGWellens (4)
  3. maartenba (2)
  4. rami_nassar (2)
  5. stiansol (2)
  6. MisterFantastic (2)
  7. satish1.v (1)
  8. raklos (1)
  9. mosessaur (1)
  10. Jos Branders (1)

Advertise Here

Microsoft Communities
Page view counter