设计模式(4)--类行为(10)--模板方法

1. 意图

定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。

模板方法使子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。

2. 两种角色

抽象类(Abstract Class)、具体类(Concrete Class)

3. 优点

3.1 一种代码复用的基本技术。提取公共行为,父类调用子类操作。

4. 缺点

N/A

5. 相关模式

5.1 工厂方法模式常被模板方法调用。

工厂方法是延迟到子类创建对象,模板方法是延迟到子类改变部分算法(行为)。

5.2 策略模式是改变整个算法,而模板方法是改变算法的一部分。

6. 代码示意(C++)
cpp 复制代码
#pragma once
#include <iostream>
using namespace std;

class AbstractClass
{
public:
	void TemplateMethod() {
		Start();
		Operation1();
		Operation2();
		End();
	}
protected:
	void Start() {
		cout << "Start in TemplateMethod" << endl;
	}
	void End() {
		cout << "End in TemplateMethod" << endl;
	}
protected:
	virtual void Operation1() {
		cout << "Operation1 in AbstractClass" << endl;
	}
	virtual void Operation2() {
		cout << "Operation2 in AbstractClass" << endl;
	}

};

class ConcreteClass : public AbstractClass
{
protected:
	virtual void Operation1() {
		cout << "Operation1 in ConcreteClass" << endl;
	}
	virtual void Operation2() {
		cout << "Operation2 in ConcreteClass" << endl;
	}

};
cpp 复制代码
#include "TemplateMethod.h"
int main() {
	AbstractClass* pClass = new ConcreteClass();
	pClass->TemplateMethod();
	delete pClass;
	return 0;
}

运行结果:

6.1 AbstractClass::TemplateMethod定义了操作框架(步骤)。

6.2 ConcreteClass可以改变中间的两个步骤Operation1、Operation2。

相关推荐
AI酒旅实战开发14 小时前
旅行 AI Agent 的 7 种设计模式:从工具调用到交易闭环
人工智能·设计模式
geovindu2 天前
rust: Functional Options Pattern
开发语言·后端·设计模式·rust·函数式选项模式·惯用法型模式
geovindu3 天前
rust: Timing Functions Pattern
开发语言·后端·设计模式·rust·计时函数模式·性能分析型模式
Mh8 天前
我是如何设计品牌站组件库的?
前端·css·设计模式
是2的10次方啊9 天前
设计模式与生活·总论:AI 能替你砌墙,替不了你打地基
设计模式
dahaihua3339 天前
用 SysML 表达航电系统架构(附建模示例)
设计模式·重构·系统架构·集成测试·需求分析·学习方法
wy_hhxx10 天前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
AAA修煤气灶刘哥10 天前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
用户6242931966211 天前
告别 Electron 臃肿与 Wireshark 老化界面:用 Rust + Tauri 2.0 构建多总线网络与现场总线深度分析仪 Omni-Probe
设计模式
是2的10次方啊11 天前
设计模式与生活㉒:暖气热不热,得一间一间摸过去
设计模式