【设计模式】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")
}
相关推荐
老蒋每日coding2 小时前
AI Agent 设计模式系列(十六)—— 资源感知优化设计模式
人工智能·设计模式·langchain
老蒋每日coding2 小时前
AI Agent 设计模式系列(十七)—— 推理设计模式
人工智能·设计模式
冷崖2 小时前
桥模式-结构型
c++·设计模式
连山齐名2 小时前
设计模式之一——堵塞队列
设计模式
会员果汁2 小时前
19.设计模式-命令模式
设计模式·命令模式
茶本无香2 小时前
设计模式之六—组合模式:构建树形结构的艺术
java·设计模式·组合模式
橘色的喵2 小时前
嵌入式 C++ 高性能流式架构的设计
数码相机·设计模式
会员果汁3 小时前
20.设计模式-职责链模式
设计模式
她和夏天一样热17 小时前
【设计模式】工厂方法模式在开发中的真实应用
设计模式·工厂方法模式
烤麻辣烫1 天前
23种设计模式(新手)-9单例模式
java·开发语言·学习·设计模式·intellij-idea