[Go版]设计模式——Template模版方法模式

目录

模板方法(Template Method)模式的说明

核心思想

定义一个算法的骨架,将一些步骤的实现延迟到子类。

设计优点

将通用的模版方法与具体的实现分离,这样可以轻松地添加新的实现,同时确保所有实现都遵循相同的模版结构。增强代码重用和扩展性。

Go语言实现该模式的示例代码

在 Go 语言中,没有传统面向对象语言中的类继承和模板方法的概念,因此无法像传统面向对象语言那样直接使用模板方法模式。Go 语言鼓励使用 接口(interface)和组合(composition) 来实现代码重用和多态性。虽然 Go 语言没有显式的模板方法,但仍然可以使用接口和组合来实现类似的模式。
源码地址: GitHub-golang版本

go 复制代码
package template

import "fmt"

// 定义模板方法的抽象结构
type AbstractClass interface {
	Step1()
	Step2()
}

// 定义模版方法
func TemplateMethod(c AbstractClass) {
	fmt.Println("模板方法")
	c.Step1()
	c.Step2()
}

main.go

go 复制代码
// ConcreteClass1 实现 AbstractClass 接口
type ConcreteClass1 struct{}

func (c *ConcreteClass1) Step1() {
	fmt.Println("具体类1的步骤1")
}

func (c *ConcreteClass1) Step2() {
	fmt.Println("具体类1的步骤2")
}

// ConcreteClass2 实现 AbstractClass 接口
type ConcreteClass2 struct{}

func (c *ConcreteClass2) Step1() {
	fmt.Println("具体类2的步骤1")
}

func (c *ConcreteClass2) Step2() {
	fmt.Println("具体类2的步骤2")
}

func main() {
	class1 := &ConcreteClass1{}
	class2 := &ConcreteClass2{}

	template.TemplateMethod(class1)
	template.TemplateMethod(class2)
}
相关推荐
a程序小傲38 分钟前
阿里Java面试被问:.Java 8中Stream API的常用操作和性能考量
开发语言·windows·python
Asus.Blogs44 分钟前
SSE + Resty + Goroutine + Channel 完整学习笔记
笔记·学习·golang
爱装代码的小瓶子1 小时前
【c++进阶】从C++98到C++11的奇妙旅程(故事科普版)
开发语言·c++
智航GIS1 小时前
2.3 运算符详解
开发语言·python
web3.08889991 小时前
接入API-自动化批量获取淘宝商品详情数据
开发语言·python
世转神风-1 小时前
qt-在字符串中指定位置插入字符串
开发语言·qt
时光呀时光慢慢走1 小时前
C# WinForms 实战:MQTTS 客户端开发(与 STM32 设备通信)
开发语言·c#
superman超哥2 小时前
仓颉类型别名的使用方法深度解析
c语言·开发语言·c++·python·仓颉
LFly_ice2 小时前
Next-4-路由导航
开发语言·前端·javascript
3824278272 小时前
python :__call__方法
开发语言·python