惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 叶小钗
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
V2EX
酷 壳 – CoolShell
酷 壳 – CoolShell
月光博客
月光博客
人人都是产品经理
人人都是产品经理
宝玉的分享
宝玉的分享
博客园 - 司徒正美
WordPress大学
WordPress大学
Microsoft Azure Blog
Microsoft Azure Blog
罗磊的独立博客
Vercel News
Vercel News
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
A
About on SuperTechFans
Apple Machine Learning Research
Apple Machine Learning Research
L
LangChain Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
Visual Studio Blog
S
SegmentFault 最新的问题
Google DeepMind News
Google DeepMind News
博客园 - 聂微东

Mohuishou

如何实现支持多集群的 Kubernetes Operator? 第三方应用如何调用我们 kubebuilder 生成的自定义资源? Kubernetes 简明教程 k8s job 为何迟迟不能结束? Go 工程化(十一) 如何优雅的写出 repo 层代码 Go 工程化(十) 如何在整洁架构中使用事务? 给博客添加章节目录 使用 Notion Database 管理静态博客文章 一个普通 Go 开发的三年 4. localhost 就一定是 localhost 么? Go可用性(七) 总结: 一张图串联可用性知识点 Go可用性(六) 熔断 10. 总结 9. kubebuilder 进阶: 源码分析 8. kubebuilder 进阶: webhook 7. kubebuilder 进阶: 测试 6. kubebuilder 实战: status & event 5. kubebuilder 实战: CRUD 4. kustomize 简明教程 3. KubeBuilder 简明教程 2. Kind: 如何快速搭建本地 K8s 开发环境? 1. Operator概述: 如何对 Kubernetes 进行扩展 Go可用性(五) 自适应限流 Go可用性(四) 漏桶算法 Go可用性(三) 令牌桶的实现 rate/limt Go可用性(二) 令牌桶原理及使用 Go可用性(一) 隔离设计 Go并发编程(十二) Singleflight Go工程化(九) 项目重构实践 Go工程化(八) 单元测试
Go模板模式14-模板模式
Mohuishou · 2020-09-23 · via Mohuishou

注:本文已发布超过一年,请注意您所使用工具的相关版本是否适用

笔记

代码实现

举个 🌰,假设我现在要做一个短信推送的系统,那么需要

  1. 检查短信字数是否超过限制
  2. 检查手机号是否正确
  3. 发送短信
  4. 返回状态

我们可以发现,在发送短信的时候由于不同的供应商调用的接口不同,所以会有一些实现上的差异,但是他的算法(业务逻辑)是固定的

Code

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
43
44
45
46
47
48
49
50
51
package template

import "fmt"

// ISMS ISMS
type ISMS interface {
send(content string, phone int) error
}

// SMS 短信发送基类
type sms struct {
ISMS
}

// Valid 校验短信字数
func (s *sms) Valid(content string) error {
if len(content) > 63 {
return fmt.Errorf("content is too long")
}
return nil
}

// Send 发送短信
func (s *sms) Send(content string, phone int) error {
if err := s.Valid(content); err != nil {
return err
}

// 调用子类的方法发送短信
return s.send(content, phone)
}

// TelecomSms 走电信通道
type TelecomSms struct {
*sms
}

// NewTelecomSms NewTelecomSms
func NewTelecomSms() *TelecomSms {
tel := &TelecomSms{}
// 这里有点绕,是因为 go 没有继承,用嵌套结构体的方法进行模拟
// 这里将子类作为接口嵌入父类,就可以让父类的模板方法 Send 调用到子类的函数
// 实际使用中,我们并不会这么写,都是采用组合+接口的方式完成类似的功能
tel.sms = &sms{ISMS: tel}
return tel
}

func (tel *TelecomSms) send(content string, phone int) error {
fmt.Println("send by telecom success")
return nil
}

单元测试

1
2
3
4
5
6
7
8
9
10
11
12
13
package template

import (
"testing"

"github.com/stretchr/testify/assert"
)

func Test_sms_Send(t *testing.T) {
tel := NewTelecomSms()
err := tel.Send("test", 1239999)
assert.NoError(t, err)
}

关注我获取更新

猜你喜欢