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

相关推荐
在未来等你20 小时前
AI Agent设计模式 Day 2:Plan-and-Execute模式:先规划后执行的智能策略
设计模式·llm·react·ai agent·plan-and-execute
在未来等你1 天前
AI Agent设计模式 Day 3:Self-Ask模式:自我提问驱动的推理链
设计模式·llm·react·ai agent·plan-and-execute
xiaodaidai丶1 天前
设计模式之策略模式
设计模式·策略模式
_院长大人_1 天前
设计模式-工厂模式
java·开发语言·设计模式
王道长服务器 | 亚马逊云2 天前
AWS + 苹果CMS:影视站建站的高效组合方案
服务器·数据库·搜索引擎·设计模式·云计算·aws
在未来等你2 天前
AI Agent设计模式 Day 1:ReAct模式:推理与行动的完美结合
设计模式·llm·react·ai agent·plan-and-execute
乐悠小码3 天前
Java设计模式精讲---03建造者模式
java·设计模式·建造者模式
_院长大人_3 天前
设计模式-代理模式
设计模式·代理模式
guangzan3 天前
TypeScript 中的单例模式
设计模式
乐悠小码4 天前
Java设计模式精讲---02抽象工厂模式
java·设计模式·抽象工厂模式