February 2012 - Posts
This blogpost is part of a series
- Template Method Pattern explanation
- Template Method Pattern example
- Template Method Pattern advanced
So we’ve looked at the Template Method Pattern with an implementation as really simple example, and another real world implementation. We have additional requirements however. We also need to transform the template so that placeholders will contain the proper text, and have the value of the placeholders customized to our customers. Let’s first look again at the executing code, so we get an idea of what API we want.
static void Main(string[] args)
{
TemplatedMessage message = new TemplatedMessage();
message.Identifier = Guid.NewGuid();
message.EmailAddress = "dvdstelt@gmail.com";
message.Template = "So you're a {{Sex}} and like to play {{BestGameEver}}.";
message.PlaceHolders.Add("Sex", "male");
message.PlaceHolders.Add("BestGameEver", "Modern Warfare 3");
MessageSenderBase emailMessageSender = new EmailMessageSender();
emailMessageSender = new MessageSenderPlaceholderParserDecorator(emailMessageSender);
emailMessageSender = new MessageSenderPlaceholderFormatterDecorator(emailMessageSender);
List<MessageSenderBase> MessageSenders = new List<MessageSenderBase>();
MessageSenders.Add(emailMessageSender);
MessageSenders.Add(new HttpPostMessageSender());
foreach (var sender in MessageSenders)
{
sender.Execute(message);
Console.WriteLine("");
}
Console.WriteLine("The final message is:\n{0}", message.Template);
Console.WriteLine("\n\nDone...\n\n");
}
It’s exactly the same code, with some additional lines added to it.
- Line 6 shows a new template in the message. You can see the placeholders {{Sex}} and {{BestGameEver}}.
- Line 8 & 9 show an additional property in the TemplatedMessage, knowing PlaceHolders, which is of type Dictionary<string, string>
- Line 11 shows the initialization of the EmailMessageSender, which hasn’t changed since last post.
- Line 12 shows the initialization of a decorator, to parse the placeholders and put in proper text from the PlaceHolders dictionary. As the decorator pattern defines, this decorator wraps the MessageSender originally used.
- Line 13 shows an additional decorator, which replaces values that our customer doesn’t understand. Our customer doesn’t understand “male”, so the MessageSenderPlaceHolderFormatterDecorator replaces its values.
- Line 16 shows the previously instantiated EmailMessageSender being added, wrapped by two decorators.
Decorator pattern and a rewrite of the template method
So without changing anything in the current MessageSenderBase class or derivates, we want to add additional functionality to perform the parsing and formatting of the placeholders. I chose to implement the decorator pattern, which is a wrapper around the original class, where both have the exact same interface. A really nice decorator example of it can be found on Ruchit Surati his weblog.
The decorator normally has an interface with a public method. Every class that implements this interface has to implement the method, as do the decorators. Our public method is the Execute method, so we’ll override that method. In the original base class, it was the template method, calling the abstract methods Initialize, SendLead and Cleanup. We don’t need this behavior anymore, so we’ll break it. Instead, we’ll use it again to recreate it as an alternative template method. We’ll now make it call a new abstract method called Decorate and after that, run the Execute method on the MessageSender we are wrapping. We’ll also override and seal the SendMessage method, because our decorators never send messages.
The end result is shown in the Visual Studio class diagram below. Normal UML diagrams show the association from the MessageSenderDecorator to the MessageSenderBase a bit clearer; Visual Studio shows it as either a reference without a property, or a property without a clear reference. I’m mentioning this because from the perspective of the decorator pattern, this is an important reference. It shows the intent that we wrap the original MessageSender inside our decorator.

The code for the decorator base class.
public abstract class MessageSenderDecorator : MessageSenderBase
{
protected MessageSenderBase MessageSender { get; private set; }
public MessageSenderDecorator(MessageSenderBase messageSender)
{
MessageSender = messageSender;
}
// This method needs concrete implementation
protected abstract void Decorate(TemplatedMessage message);
// Close the SendMessage method, decorators don't send messages!
protected sealed override void SendMessage() { }
public override void Execute(TemplatedMessage message)
{
Decorate(message);
MessageSender.Execute(message);
}
}
Now we’ll implement the first decorator.
public class MessageSenderPlaceholderParserDecorator : MessageSenderDecorator
{
public MessageSenderPlaceholderParserDecorator(MessageSenderBase messageSender) : base(messageSender) { }
protected override void Decorate(TemplatedMessage message)
{
message.Template = ParseTemplate(message.Template, message.PlaceHolders);
}
private string ParseTemplate(string template, Dictionary<string, string> placeHolders)
{
foreach (var placeholder in placeHolders)
{
var key = string.Format("{{{{{0}}}}}", placeholder.Key);
var value = placeholder.Value.ToString();
template = template.Replace(key, value);
}
return template;
}
}
As you can see, our real decorator implementation now implements the Decorate method, which we had to implement based on our base class. What this class do is simply replace every placeholder with the actual value. Going back to our first code snippet of the static Main method, you can see that we first wrap the EmailMessageSender into the decorator to parse all placeholders. Then we wrap it inside the second decorator, for parsing all values of the placeholders. If we turn this around, first the template message will be parsed, and only then the values in the PlaceHolders dictionary will be replace. This is of course too late, and this is a bit of a downside to the decorator. When writing completely procedural code, not many developers would make this mistake. With the decorator pattern, you’ll have to think a bit about it. The intent here isn’t as clear as you’d want it to be.
Conclusion
It’s always hard for new developers to write software like this. From my own experience, when first coming into contact with design patterns, you start to search for a design pattern based on a problem you have. After a lot of experience with some design patterns, you’ll start thinking the other way around. Instead of starting with a problem and finding a good design pattern that solves it, you’ll immediately start thinking about a design pattern that matches the problem you’re solving. Again, this is experience and takes practice. Try playing around with design patterns until you know them and know what they do. It’s not that important to be able to draw them out in a UML class diagram, from the top of your head. As long as you can remember which problems they solve and how you should roughly implement them.
Speaking of finding the right design pattern for a problem; this could very likely be solved in multiple ways, with different patterns. But it’s an example of how a problem could be solved using design patterns. I still have to completely implement this into our system and might come up with alternate solutions altogether. But I started this as a proof of concept and it seemed nice enough to blog about it. I hope you learned something from it, because that is still the reason for me to blog! ;-)
Download the source here.
This blogpost is part of a series
- Template Method Pattern explanation
- Template Method Pattern example
- Template Method Pattern advanced
So in my previous post I explained how I change the template method pattern a bit with protected abstract methods. In this post I’ll explain why I used this pattern and how I chose to implement it.
Requirements
At my current employer we send a lot of messages to customers. It varies per customer how message are being send. Some want a simple email, others want an xml document in their email, others want an xml document over HttpPost and others want us to send the message directly into a customers system, for example SalesForce. Most customers only have one option, some customers want multiple options.
When the software was first build, we only did send messages via email. A very simple solution was build. As more and more variations were required, a better solution was required. In our system, information is gathered, which is being inserted into the messages we send. We needed templated messages which contain placeholders. However, as some customers receive XML fed directly into their system, we needed to change some placeholder values, as not every system understands our values “male” and “female”, but rather have “1” or “0” for these values. Technical requirements are also important. We need to be able to store a successful or failed result to a datastore and needed to log exceptions as well.
First, we’ll have a look at how we solve different transport mechanisms. Additional requirements for templates will be explained in another post, where we’ll add the decorator pattern and implement an additional template method pattern.
Perhaps you’ll understand better what I implemented, if I show you the code that is executed to actually send out everything. In our system, we dynamically define which modules are being executed, in the following code I’ve defined a message sender for email and HttpPost.
static void Main(string[] args)
{
TemplatedMessage message = new TemplatedMessage();
message.Identifier = Guid.NewGuid();
message.EmailAddress = "dvdstelt@gmail.com";
message.Template = "Dude!";
List<MessageSenderBase> MessageSenders = new List<MessageSenderBase>();
MessageSenders.Add(new EmailMessageSender());
MessageSenders.Add(new HttpPostMessageSender());
foreach (var sender in MessageSenders)
{
sender.Execute(message);
}
Console.WriteLine("\n\nDone...\n\n");
}
First the message is defined. It contains a guid for reference, an email address and a template. The template is the actual message. Then we initialize the two message senders and execute these one at a time in the foreach loop. Let’s have a look at the implementation of the base class.
public abstract class MessageSenderBase
{
protected TemplatedMessage Message { get; private set; }
public virtual void Execute(TemplatedMessage message)
{
Message = message;
Initialize();
SendMessage();
CleanUp();
}
protected abstract void SendMessage();
private void Initialize()
{
if (Message == null) throw new InvalidOperationException("Message cannot be null");
Console.WriteLine("Initializing {0} for MessageId [{1}].", this.GetType().Name, Message.Identifier);
}
private void CleanUp()
{
Console.WriteLine("Cleaning up {0} for MessageId [{1}].", this.GetType().Name, Message.Identifier);
Console.WriteLine("\tSaving state changes to datastore...");
Console.WriteLine("\tSaving result to logfile...");
}
}
The base class of course cannot be instantiated, so we made it abstract. The message that was created in the first codeblock, is stored in a protected property (line 3), so we don’t have to pass it to every single method. Normally I don’t like vague global variables, but as it’s protected, I don’t see real harm. The SendMessage method is the abstract method that the derived classes must use to write code that they are responsible for. The Initialize method has a guard for a proper message, some might want this to be in the Execute method.
The Initialize and CleanUp method don’t do anything in the above code, but normally you’d use those for logging, storing state and exception handling. We have Enterprise Library code there for logging, and we log the current progress to a trace listener, rolling textfile and database. With the regular trace listener we can use DebugView from Sysinternals for live tracing.
The Execute method is the only public method. It is the method that will be executed and used to run every method in the right order. This will always run the SendMessage method of a derived class, simply because this base class has no implementation. So let’s have a look at our email sender.
public class EmailMessageSender : MessageSenderBase
{
protected override void SendMessage()
{
Console.WriteLine("I'm sending the message via email.");
}
}
This could not be a lot simpler. Of course the actual implementation isn’t here, but that’s the point of the example. There’s no other code in this class, but the code that’s related to sending the message over email. This is completely according to the Single Responsibility Principle. When a customer requires an additional way of sending the message, we don’t need to change any code. We simply add another class with the required functionality. That’s Open/Closed Principle for you!
I hope you understand why I like this implementation of the Template Method Pattern. For deriving classes, it’s completely clear what to implement. For external applications, it’s completely clear what to execute. In the last part of the Template Method Pattern series, we’ll introduce additional functionality and solve one problem with the decorator pattern and another template method pattern implementation. That post also includes a download if you want to play around with the code.
This blogpost is part of a series
- Template Method Pattern explanation
- Template Method Pattern example
- Template Method Pattern advanced
I’ve recently read a post about someone who hated the Template Method Pattern, because its intent wasn’t revealed. When based on the many examples out there, you might agree with this. First let’s see what the theoretical intent of the pattern is. You can look it up on wikipedia, but recently I’ve come across sourcemaking.com where a lot of patterns are described and I really like that site! Besides a good theoretical explanation it also has examples in many languages. About the intent of the Template Method Pattern it says:
Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure. - Base class declares algorithm ‘placeholders’, and derived classes implement the placeholders.
So you define a skeleton and derived classes have to implement the placeholders. The problem with the default pattern is that everything is public. This is something I don’t like myself. I’d rather have a protected and abstract skeleton so that derived classes exactly know what to implement, but external classes only see the public template method from the base class.
public abstract class AbstractClass
{
protected abstract void StepOne();
protected abstract void StepTwo();
protected abstract void StepThree();
public void TemplateMethod()
{
StepOne();
StepTwo();
StepThree();
}
}
As you can see the skeleton (the StepOne, StepTwo & StepThree methods), is protected and abstract. Protected means the methods are private for outsiders, only derived classes can see the methods. Abstract means it has no implementation, but derived classes must implement it. The TemplateMethod however is public and can be called. Let’s have a look at an implementation.
public class ConcreteClass : AbstractClass
{
protected override void StepOne()
{
Console.WriteLine("Inside Step 1");
}
protected override void StepTwo()
{
Console.WriteLine("Inside Step 2");
}
protected override void StepThree()
{
Console.WriteLine("Inside Step 3");
}
}
Here you can see that the template method is nowhere to be seen, but the abstract methods were implemented. When the template method is executed, all three methods will be called. In a console application this would look like this.
static void Main(string[] args)
{
AbstractClass myObject = new ConcreteClass();
myObject.TemplateMethod();
Console.WriteLine("Finished, press a key to continue...");
Console.ReadKey();
}
This is of course again one of the over simplified examples, in a following post I will show a concrete example that I had to develop for the company I work for.