【设计模式】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")
}
相关推荐
FLZJ_KL7 小时前
【设计模式】【创建型模式】抽象工厂模式(Abstract Factory)
java·设计模式·抽象工厂模式
攻城狮7号7 小时前
【第四节】C++设计模式(创建型模式)-Builder(建造者)模式
c++·设计模式·建造者模式
Nita.7 小时前
设计模式| 观察者模式 Observer Pattern详解
观察者模式·设计模式·c#
找了一圈尾巴18 小时前
设计模式-组合模式、模板模式
设计模式·组合模式
float_六七20 小时前
Java——单例类设计模式
java·单例模式·设计模式
老菜鸟的每一天20 小时前
创建型模式-Prototype 模式(原型模式)
设计模式·原型模式
码熔burning21 小时前
(五)趣学设计模式 之 建造者模式!
java·设计模式·建造者模式
黑不溜秋的1 天前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
付聪12101 天前
策略模式介绍和代码示例
设计模式
ThereIsNoCode1 天前
「软件设计模式」状态模式(State)
设计模式·状态模式