[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)
}
相关推荐
花酒锄作田1 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
郑州光合科技余经理1 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1231 天前
matlab画图工具
开发语言·matlab
dustcell.1 天前
haproxy七层代理
java·开发语言·前端
norlan_jame1 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone1 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054961 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月1 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237171 天前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian1 天前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript