What is the need for Template Method Pattern in C#?

Most of you might have already implemented this template method pattern in your program unknowingly. Have you used inheritance in your program with an intension that one or more methods of the base class have to be implemented by its derived class? Then you have used template method pattern.



Simple example to template method pattern will be an abstract base class whose methods are implemented in its derived class. This example is demonstrated below:

abstract class baseClass {
public abstract void abstractMethod1();
public void templateMethod() {
Console.WriteLine(“Executing template method…”);
abstractMethod1();
}
}
class derivedClass:baseClass {
public override void abstractMethod1() {
Console.WriteLine(“abstractMethod1 is implemented by derivedClass”);
}
}
class testClass {
baseClass obj = new derivedClass();
obj.templateMethod();
}
Output of this code will be:
Executing template method…
abstractMethod1 is implemented by derivedClass

In this example, templateMethod is implemented by baseClass but the method abstractMethod1 is not implemented by baseClass. It is expected to be implemented by the derived class of baseClass. That is where template method pattern is utilized.

| What is the need for Bridge Pattern in C#? | What is the need for Builder Pattern in C#? | What is the need for Chain of Responsibility Pattern in C#? | What is the need for Command Pattern in C#? | What is the need for Composite Pattern in C#? | What is the need for Decorator Pattern in C#? | What is the need for Flyweight Pattern in C#? | What is the need for Interpreter Pattern in C#? | What is the need for Iterator Pattern in C#? | What is the need for Mediator Pattern in C#? | What is the need for Memento Pattern in C#? | What is the need for Prototype Pattern in C#? | What is the need for State Pattern in C#? | What is the need for Strategy Pattern in C#? | What is the need for Template Method Pattern in C#? | What is the need for unsafe code in C#? | What is the purpose of assert() in C#? | What is the purpose of AutoResetEvent in .NET? | What is the purpose of Console.ReadLine() in C#? | What is the purpose of machine.config file in .NET? |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.