设计模式(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。

相关推荐
胡萝卜术5 小时前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
亦暖筑序1 天前
Java 8老系统Browser Agent实战:三层拦截把AI操作后台变成可审计流程
java·后端·设计模式
青禾网络3 天前
Web 前端如何接入 AI 音效生成:从零到可用的完整方案
人工智能·设计模式
ZJPRENO4 天前
吃透软件开发六大设计原则,告别烂代码
设计模式
咖啡八杯4 天前
GoF设计模式——命令模式
java·设计模式·架构
花椒技术5 天前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
艺艺生辉5 天前
迭代器模式-"我也想被增强for循环"
设计模式
咖啡八杯7 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
槑有老呆8 天前
别再手搓 Prompt 了,那个叫"手动挡循环"
设计模式