TemplateMethod (template method - behavior pattern)

The template method is the most important and concise design pattern, and it is widely used.
motivation
insert image description here
intention
insert image description here
structure
insert image description here
code
framework developer

//框架开发者-先开发
abstract class Vehical
{
    
    
    protected abstract void StartUp();
    protected abstract void Run();
    protected abstract void Turn(int degree);
    protected abstract void Stop();

    public void Test()
    {
    
    
        //测试数据记录
        StartUp();//晚绑定————留给应用程序开发人员,扩展点
        //测试数据记录
        Run();//晚绑定————留给应用程序开发人员,扩展点
        //测试数据记录
        Stop();//晚绑定————留给应用程序开发人员,扩展点
        //测试数据记录
        //生成测试数据
    }
}

class VehicalTestFramework
{
    
    
    public static void DoTest(Vehical vehical)
    {
    
    
        vehical.Test();
    }
}

application developer

//应用程序开发人员-晚开发
class HongQiCar:Vehical
{
    
    
    protected override void StartUp()
    {
    
    
    }
    protected override void Run()
    {
    
    
    }
    protected override void Turn(int degree)
    {
    
    
    }
    protected override void Stop()
    {
    
    
    }
}
class App
{
    
    
    public void Use()
    {
    
    
        VehicalTestFramework.DoTest(new HongQiCar());
    }
}

Point
insert image description here
virtual method - extension point, set to Protected

Abstract method: no concrete implementation
Virtual method: has default implementation

Creational mode: creating object types and concrete implementations (interfaces are stable)
Structural mode: interface changes

Guess you like

Origin blog.csdn.net/weixin_51565051/article/details/131823506