[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)
}
相关推荐
wjs20248 分钟前
DOM CDATA
开发语言
Tingjct10 分钟前
【初阶数据结构-二叉树】
c语言·开发语言·数据结构·算法
猷咪36 分钟前
C++基础
开发语言·c++
IT·小灰灰37 分钟前
30行PHP,利用硅基流动API,网页客服瞬间上线
开发语言·人工智能·aigc·php
快点好好学习吧39 分钟前
phpize 依赖 php-config 获取 PHP 信息的庖丁解牛
android·开发语言·php
秦老师Q40 分钟前
php入门教程(超详细,一篇就够了!!!)
开发语言·mysql·php·db
烟锁池塘柳040 分钟前
解决Google Scholar “We‘re sorry... but your computer or network may be sending automated queries.”的问题
开发语言
是誰萆微了承諾40 分钟前
php 对接deepseek
android·开发语言·php
2601_9498683644 分钟前
Flutter for OpenHarmony 电子合同签署App实战 - 已签合同实现
java·开发语言·flutter
星火开发设计1 小时前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识