Go 实现常用设计模式(七)模板方法模式
模版方法 (template)
意图:
定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
关键代码:
通用步骤在抽象类中实现,变化的步骤在具体的子类中实现
应用实例:
- 做饭,打开煤气,开火,(做饭), 关火,关闭煤气。除了做饭其他步骤都是相同的,抽到抽象类中实现
- spring 中对 Hibernate 的支持,将一些已经定好的方法封装起来,比如开启事务、获取 Session、关闭 Session
Go实现模板方法
package template
import "fmt"
type Cooker interface {
open()
fire()
cooke()
outfire()
close()
}
// 类似于一个抽象类
type CookMenu struct {
}
func (CookMenu) open() {
fmt.Println("打开开关")
}
func (CookMenu) fire() {
fmt.Println("开火")
}
// 做菜,交给具体的子类实现
func (CookMenu) cooke() {
}
func (CookMenu) outfire() {
fmt.Println("关火")
}
func (CookMenu) close() {
fmt.Println("关闭开关")
}
// 封装具体步骤
func doCook(cook Cooker) {
cook.open()
cook.fire()
cook.cooke()
cook.outfire()
cook.close()
}
type XiHongShi struct {
CookMenu
}
func (*XiHongShi) cooke() {
fmt.Println("做西红柿")
}
type ChaoJiDan struct {
CookMenu
}
func (ChaoJiDan) cooke() {
fmt.Println("做炒鸡蛋")
}
测试用例
package template
import "testing"
func TestTemplate(t *testing.T) {
// 做西红柿
xihongshi := &XiHongShi{}
doCook(xihongshi)
// 做炒鸡蛋
chaojidan := &ChaoJiDan{}
doCook(chaojidan)
}
具体代码
更详细的代码可参考:https://github.com/pibigstar/go-demo 里面包含了 Go 常用的设计模式、Go 面试易错点、简单的小项目(区块链,爬虫等)、还有各种第三方的对接(redis、sms、nsq、elsticsearch、alipay、oss...),如果对你有所帮助,请给个 Star
,你的支持,是我最大的动力!
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: