Click here to Skip to main content
15,879,095 members
Articles / Programming Languages / C#

"Please Don’t Fail Me!" - Decorator Cries Out to Template Method

,
Rate me:
Please Sign up or sign in to vote.
4.68/5 (13 votes)
13 Sep 2009CPOL6 min read 55.1K   145   20  
Are your classes that implement the Template Method Design Pattern "Decorator aware"?
using System;

namespace HypotheticalShapeLib
{
   public abstract class Shape
   {
      public  string TypeName { get; private set; }

      public Shape(string typeName)
      {
         TypeName = typeName;

         Console.WriteLine("Shape ctor");
      }

      // This is a template method
      public void Draw()
      {
         Console.WriteLine(string.Format("Drawing {0}", TypeName));

         CreateDC();
         InitDC();
         Paint();
         ReleaseDC();
      }

      // The following methods have been marked as protected internal so that
      // only derived classes or any classes within the containing assembly can 
      // access these methods.
      // If these methods are not marked internal, the Decorator pattern cannot be implemented
      // on the Shape class. Marking as internal implies that that ShapeDecoratorBase has to be implemented
      // in the same assembly.
      protected internal abstract void CreateDC();
      protected internal abstract void InitDC();
      protected internal abstract void Paint();
      protected internal abstract void ReleaseDC();
   };

   public class Circle : Shape
   {
      public Circle()
         : base("Circle")
      {
         Console.WriteLine("Circle ctor");
      }

      protected internal override void CreateDC()
      {
         Console.WriteLine("Circle Create DC");
      }

      protected internal override void InitDC()
      {
         Console.WriteLine("Circle InitDC");
      }

      protected internal override void Paint()
      {
         Console.WriteLine("Circle PaintDC");
      }

      protected internal override void ReleaseDC()
      {
         Console.WriteLine("Circle ReleaseDC");
      }
   }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Written By
Technical Lead HCL Technologies LTD
India India
I am Sanjeev Venkat working for HCL Technologies since 2003. I've 9 years of experience in Software Development. My core expertise include Windows Device Drivers, COM, C++, .NET.

Comments and Discussions