( Design Patterns ) Behavioral D
2016-10-11 本文已影响0人
乔什华
Definition
Defines the steps of an algorithm and allows subclasses to provide the implementation for one or more steps.
Components
- AbstractClass: Defines a group of basic methods and template methods. Template Methods define the order of executing basic methods. Basic Methods let subclasses to override or implement。
-
ConcreteClass:Inheret from Abstract Class that implements the basic methods which defined by Abstract Class.
Template Method Pattern UML
Code
//Abstract Class
public abstract class AbstractClass
{
//basic methods
protected abstract void SimpleMethod1();
protected abstract void SimpleMethod2();
//template methods
public void templateMethod()
{
SimpleMethod1();
SimpleMethod2();
}
}
//Concrete methods
public class ConcreteClass : AbstractClass
{
protected override void SimpleMethod1()
{
Console.WriteLine("method1");
}
protected override void SimpleMethod2()
{
Console.WriteLine("method2");
}
}
//Client class
public class Client
{
public static void Main(String[] args)
{
ConcreteClass class1 = new ConcreteClass();
class1.templateMethod();
}
}
Advantages
- Open Close Principle.
- The behavior(orders of executing basic methods) is controlled by parent class, subclasses are only for implementation. Easy to extend.
Reference
Design Patterns 1 of 3 - Creational Design Patterns - CodeProject
Head First Design Patterns - O'Reilly Media