模板方法模式

The Template Method design pattern defines the skeleton of an algorithm in an operation, defering some steps to subclasses. This pattern lets subclasses redefine certain steps of an algorithm wihout changing the algorithm's structure.

模板方法设计模式在操作中定义了算法骨架,将一些步骤推迟到子类中。这种模式允许子类在不改变算法结构的情况下重新定义算法的某些步骤。

Template Method Design Pattern defines a sequence of steps of an algorithm and allows the subclasses to override the steps but is not allowed to change the sequence.

UML Class Diagram

 AbstractClass : This is going to be an abstract class that contains the template method which defines teh steps to create the product. It also contains abstract method for each or the steps that going to be implemented by subclasses.

 ConcreteClass: There are going to be concrete classes and these classes are inherited from the abstract class and override the abstract class abstract methods in their own way.

  Client: The Client is going to use the AbstractClass template method to create different products.

Structure Code IN C#?

 public abstract class AbstractClass
    {
        public abstract void PrimitiveOperation1();
        public abstract void PrimitiveOperation2();

        public void TemplateMethod()
        {
            PrimitiveOperation1();
            PrimitiveOperation2();
        }
    }
Abstract Class
public class ConcreteClassA : AbstractClass
    {
        public override void PrimitiveOperation1()
        {
            Console.WriteLine($"{typeof(ConcreteClassA).Name} Primitive Operation1");
        }

        public override void PrimitiveOperation2()
        {
            Console.WriteLine($"{typeof(ConcreteClassA).Name} Primitive Operation2");
        }
    }

    public class ConcreteClassB : AbstractClass
    {
        public override void PrimitiveOperation1()
        {
            Console.WriteLine($"{typeof(ConcreteClassB).Name} Primitive Operation1");
        }

        public override void PrimitiveOperation2()
        {
            Console.WriteLine($"{typeof(ConcreteClassB).Name} Primitive Operation2");
        }
    }
ConcreteClass

 

When to use Template Method Design Patterns in Real-Time Applications?

  • We have a method in the base class that calls a bunch of other methods that are either abstract or empty in a particular sequence.
  • we required an abstract view of an algorithm, but the implementation of the algorithm varies according to the child classes.
posted @ 2023-06-03 21:29  云霄宇霁  阅读(7)  评论(0编辑  收藏  举报