【设计模式】13、template 模板模式

文章目录

  • [十三、template 模板模式](#十三、template 模板模式)
    • [13.1 ppl](#13.1 ppl)
      • [13.1.1 目录层级](#13.1.1 目录层级)
      • [13.1.2 ppl_test.go](#13.1.2 ppl_test.go)
      • [13.1.3 ppl.go](#13.1.3 ppl.go)
      • [13.1.4 llm_ppl.go](#13.1.4 llm_ppl.go)
      • [13.1.5 ocr_ppl.go](#13.1.5 ocr_ppl.go)

十三、template 模板模式

https://refactoringguru.cn/design-patterns/template-method

如果是一套标准流程, 但有多种实现, 可以用 template 模板模式.

例如, 如果要开发一个数据挖掘程序, 支持输入 word, csv, pdf. 他们其实是相同的流程(如打开文件, 读取数据, 转换数据, 输出数据).

因为每种类别的流程相同, 所以每种类别的实现有很多重复代码.

为了消除这些重复代码, 可以定义基类, 实现通用的逻辑, 如果有个性化的逻辑再覆盖.

13.1 ppl

https://refactoringguru.cn/design-patterns/template-method/go/example

go 虽然没有继承, 但可通过 interface 和 组合实现. 框架如下:

go 复制代码
type iTemplate interface {  
    step1()    step2()}  

// 外部使用的基类  
type wrapper struct {  
    template iTemplate}  

// 基类的方法: 串联整个流程  
func (w *wrapper) run() {  
    w.template.step1()    w.template.step2()}  

然后有如下具体实现:

go 复制代码
type impl1 struct {}  
func (i *impl1) step1() {}  
func (i *impl1) step2() {}  

type impl2 struct {}  
func (i *impl2) step1() {}  
func (i *impl2) step2() {}  

使用:

go 复制代码
// 第一种实现  
w := &wrapper{template: &impl1{}}  
w.run()  

// 第二种实现  
w := &wrapper{template: &impl2{}}  
w.run()  

13.1.1 目录层级

bash 复制代码
├── llm_ppl.go
├── ocr_ppl.go
├── ppl.go
├── ppl_test.go
└── readme.md

13.1.2 ppl_test.go

go 复制代码
package _31ppl

import "testing"

func TestLLMPipeline(t *testing.T) {
	e := &aiEngine{ppl: &llmPipeline{}}
	e.runPipeline()

	e = &aiEngine{ppl: &ocrPipeline{}}
	e.runPipeline()
}

13.1.3 ppl.go

go 复制代码
package _31ppl

// imagePipeline 图像处理流程
type imagePipeline interface {
	// 检测
	detect()
	// 分类
	classification()
}

type aiEngine struct {
	ppl imagePipeline
}

func (e *aiEngine) runPipeline() {
	e.ppl.detect()
	e.ppl.classification()
}

13.1.4 llm_ppl.go

go 复制代码
package _31ppl

import "fmt"

type llmPipeline struct{}

func (ppl *llmPipeline) detect() {
	fmt.Println("llmPipeline detect")
}

func (ppl *llmPipeline) classification() {
	fmt.Println("llmPipeline classification")
}

13.1.5 ocr_ppl.go

go 复制代码
package _31ppl

import "fmt"

type ocrPipeline struct{}

func (ppl *ocrPipeline) detect() {
	fmt.Println("ocrPipeline detect")
}

func (ppl *ocrPipeline) classification() {
	fmt.Println("ocrPipeline classification")
}
相关推荐
爱学习的小熊猫_29 分钟前
设计模式之责任链模式
设计模式·责任链模式
闲不住的李先森1 小时前
乐观更新
前端·react.js·设计模式
数据智能老司机4 小时前
数据工程设计模式——实时摄取与处理
大数据·设计模式·架构
Asort6 小时前
JavaScript设计模式(七)——桥接模式:解耦抽象与实现的优雅之道
前端·javascript·设计模式
原则猫8 小时前
单例模式工程运用
前端·设计模式
charlie11451419118 小时前
精读C++20设计模式:行为型设计模式:中介者模式
c++·学习·设计模式·c++20·中介者模式
虫师c21 小时前
分布式系统设计模式:从理论到实践
微服务·设计模式·系统架构·高可用·分布式系统
半旧夜夏21 小时前
【设计模式】核心设计模式实战
java·spring boot·设计模式
ThisIsMirror1 天前
设计模式简要介绍
设计模式
Lei活在当下1 天前
【业务场景架构实战】7. 多代智能手表适配:Android APP 表盘编辑页的功能驱动设计
android·设计模式·架构