Wednesday, July 20, 2011

More on Template Design Pattern

Hi guys,
hope you liked the last article, which included a modification the Template method pattern.

I would like to continue the same topic and expose another useful implementation of the pattern. It's a very basic example of OOP - nothing advanced.

What do we want solve
In web applications you often have to expose your data through different formats - like XML, JSON or RSS. Every time, you need to get the Response of the page, clear it, fill it with contents and then end the Response.
This can be an error prone information, as you have to take care of some details like "Flushing" the response before ending it. It would be nice, if you could skip these details after you've written and tested them once.

Response Template implementation
My approach to this problem was to create a simple ResponseTemplate class, which is actually a plain implementation of the Template design pattern. Below is a sample implementation:

public abstract class ResponseTemplate
{
protected HttpResponse Response { get; private set; }

public ResponseTemplate(HttpResponse httpResponse)
{
this.Response = httpResponse;
}

public void WriteResponse()
{
this.Response.Clear();

SetContentType();

Write();

this.Response.Flush();
this.Response.End();
}

internal abstract void Write();

internal abstract void SetContentType();
}


Using this class, you forget about the details. You just pass the HttpResponse and implement the SetContentType() and Write() methods.

Now if I would want to return an XML I would write a concrete implementation inheriting the ResponseTemplate class:
public class XmlResponse : ResponseTemplate
{
private string XML { get; set; }

public XmlResponse(HttpResponse httpResponse, XDocument doc)
: base(httpResponse)
{
this.XML = doc.ToString();
}

public XmlResponse(HttpResponse httpResponse, string xml)
: base(httpResponse)
{
this.XML = xml;
}

internal override void Write()
{
base.Response.Write(this.XML);
}

internal override void SetContentType()
{
base.Response.ContentType = ContentType.Xml;
}
}


In the end, these are all just plain and very simple OOP principles. The main purpose why I continue making them look harder by calling them things like "Template Design Pattern" is that this facilitates your communication with the other developers. But, this is a whole different topic, worth writing some day.

Happy coding!