SoFunction
Updated on 2025-03-08

C# Template Method Pattern Example Tutorial

This article describes the implementation method of C# template method mode in a simple example form, and shares it with you for your reference. The specific implementation method is as follows:

Here we assume that we want to make a braised pork dish. There are many ways to make it. There are the same parts in different ways, such as adding oil, meat, seasonings, etc. There are also differences, such as some methods of putting cola, some methods of putting sweet sauce, etc.

First, extract an abstract class. This class not only has various steps to make braised pork, but also summarizes each step into another method. We call this method the template method.in addition,In the template method, use abstract methods first for some uncertain aspects

public abstract class HongShaoRou
{
    public void MakeHongShaoRou()
    {
      You();
      Rou();
      Others();
      TiaoLiao();
    }
    public void You()
    {
      ("Put in oil");
    }
    public void Rou()
    {
      ("Put in meat");
    }
    public abstract void Others();
    public void TiaoLiao()
    {
      ("Put in seasoning");
    }
}

If there is a kind of "Sichuan Braised Pork" that is made of sesame paste.

public class SiChuangHongShaoRou : HongShaoRou
{
    public override void Others()
    {
      ("Put in sesame paste");
    }
}

The client just needs to call the template method of the abstract class.

class Program
{
    static void Main(string[] args)
    {
      HongShaoRou hongShaoRou = new SiChuangHongShaoRou();
      ();
      ();
    }
}

I hope this article will be helpful to everyone's C# programming learning.