【设计模式】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")
}
相关推荐
蜡笔小新..16 小时前
【设计模式】软件设计原则——开闭原则&里氏替换&单一职责
java·设计模式·开闭原则·单一职责原则
性感博主在线瞎搞18 小时前
【面向对象】设计模式概念和分类
设计模式·面向对象·中级软件设计师·设计方法
lucifer31118 小时前
JavaScript 中的组合模式(十)
javascript·设计模式
lucifer31118 小时前
JavaScript 中的装饰器模式(十一)
javascript·设计模式
蜡笔小新..19 小时前
【设计模式】软件设计原则——依赖倒置&合成复用
设计模式·依赖倒置原则·合成复用原则
刷帅耍帅19 小时前
设计模式-代理模式
设计模式·代理模式
神的孩子都在歌唱1 天前
行为设计模式 -观察者模式- JAVA
java·观察者模式·设计模式
刷帅耍帅1 天前
设计模式-解释器模式
设计模式·解释器模式
刷帅耍帅1 天前
设计模式-备忘录模式
设计模式·备忘录模式