行为型:模板模式

2022-10-18 Golang Go 进阶

# 一、模板的定义

模版模式(Template Pattern)定义一个操作中算法的骨架,而将一些步骤延迟到子类中。这种方法让子类在不改变一个算法结构的情况下,就能重新定义该算法的某些特定步骤。这里的“算法”,可以理解为广义上的“业务逻辑”。

简单来说,模板模式就是将一个类中能够公共使用的方法放置在抽象类中实现,将不能公共使用的方法作为抽象方法,强制子类去实现,这样就做到了将一个类作为一个模板,让开发者去填充需要填充的地方。

# 二、使用场景

# 2.1 复用

复用指的是,所有的子类可以复用父类中提供的模板方法的代码。

# 2.2 扩展

扩展指的是,框架通过模板模式提供功能扩展点,让框架用户可以在不修改框架源码的情况下,基于扩展点定制化框架的功能。

# 三、模板的实现

package template

import "fmt"

// Cooker 全部接口定义
type Cooker interface {
	fire()
	cook()
	outfire()
}

// CookMenu 可看作一个抽象类
type CookMenu struct{}

func (c *CookMenu) fire() {
	fmt.Println("开火")
}

// 交给具体的子类实现
func (c *CookMenu) cook() {
	panic("implement me")
}

func (c *CookMenu) outfire() {
	fmt.Println("关火")
}

// DoCook 封装具体步骤
func DoCook(cook Cooker) {
	cook.fire()
	cook.cook()
	cook.outfire()
}

// Potato 使用组合来模拟继承
type Potato struct {
	CookMenu
}

func (f Potato) cook() {
	fmt.Println("做土豆")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

使用方法如下:

package template

import "testing"

func TestTemplate(t *testing.T) {
	potato := &Potato{}
	DoCook(potato)
}
1
2
3
4
5
6
7
8

# 四、参考资料

Last Updated: 2023-01-28 4:31:25