( Design Patterns ) Behavioral Design Patterns 4 -- Template Method Pattern

Definition

Defines the steps of an algorithm and allows subclasses to provide the implementation for one or more steps.

Components

  1. 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。
  2. ConcreteClass:Inheret from Abstract Class that implements the basic methods which defined by Abstract Class.
    ( Design Patterns ) Behavioral Design Patterns 4 -- Template Method Pattern_第1张图片
    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

  1. Open Close Principle.
  2. 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

你可能感兴趣的:(( Design Patterns ) Behavioral Design Patterns 4 -- Template Method Pattern)