Template Method Design Pattern in C# with Real World Example

Template Method is a ** behavioural design pattern**. Template Method design pattern is used to create a method stub and defer some of the implementation steps to the subclasses.

The original ASP.NET paradigm, now known as Web Forms, used the template method heavily. Every control and page had a series of events in its lifecycle that developers could extend, but application developers didn’t have control over the lifecycle itself. To make the demo simple, I am using a few methods of ASP.NET webforms and I will only focus on the OnPrerender method.

Let’s implement the pattern in c#

Control.OnPreRender(EventArgs) Method

public abstract class BasePage
{
	private StringBuilder builder = new StringBuilder();
	protected StringBuilder Content
	{
		get
		{
			return builder;
		}
	}
	public BasePage() {}

	protected virtual void OnLoad()
	{
		builder.Append($"<html><head>");
	}
	protected virtual void OnUnload()
	{
		builder.Clear();
	}
	protected virtual void OnPreRender()
	{
		builder.Append("<script/></head><body>");		
	    builder.Append($"<h1>Hello </h1>");
	}
	public string Render()
	{
		OnLoad();
		OnPreRender();
		builder.Append($"</body></html>");
		var result= builder.ToString();
		OnUnload();
		return result;
		
	}

}

Let’s create a page class and run the application.

public class Page: BasePage
{
	public Page() {}
	
}
void Main()
{
	var page = new Page();
	Console.WriteLine(page.Render());

}

If you run the application, you will see the following output.

<html>
    <head>
        <script />
    </head>
    <body>
        <h1>Hello</h1>
    </body>
</html>

Let’s assume If you want to add extra information before the render method is called, then you can override the OnPreRender method and add the additional information. This method will be called at the right place.

In the below example, I am adding extra information in the render class.

public class Page: BasePage
{
	public Page() {}
	protected override void OnPreRender()
	{
		base.OnPreRender();
		Content.Append("codeguru");
	}
}

void Main()
{
	var page = new Page();
	Console.WriteLine(page.Render());

}

<html>
    <head>
        <script />
    </head>
    <body>
        <h1>Hello</h1>
        <p>codeguru</p>
    </body>
</html>

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم