Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Template Method

0.00/5 (No votes)
12 Oct 2013 1  
Template MethodThe Template Method is know as a behavioral pattern which lets subclasses implement behaviour that can vary. In the example below we

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

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

        MakeDrink(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 SubEnd 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 SubEnd 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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here