【设计模式】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")
}
相关推荐
王道长服务器 | 亚马逊云13 小时前
AWS + 苹果CMS:影视站建站的高效组合方案
服务器·数据库·搜索引擎·设计模式·云计算·aws
在未来等你14 小时前
AI Agent设计模式 Day 1:ReAct模式:推理与行动的完美结合
设计模式·llm·react·ai agent·plan-and-execute
乐悠小码1 天前
Java设计模式精讲---03建造者模式
java·设计模式·建造者模式
_院长大人_1 天前
设计模式-代理模式
设计模式·代理模式
guangzan1 天前
TypeScript 中的单例模式
设计模式
乐悠小码2 天前
Java设计模式精讲---02抽象工厂模式
java·设计模式·抽象工厂模式
乙己4072 天前
设计模式——原型模式(prototype)
设计模式·原型模式
⑩-2 天前
浅学Java-设计模式
java·开发语言·设计模式
攻心的子乐2 天前
软考 关于23种设计模式
java·开发语言·设计模式
成钰3 天前
设计模式之单例模式:一个类就只有一个实例
单例模式·设计模式