Go设计模式07-桥接模式

笔记

代码实现

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
package bridge

// IMsgSender IMsgSender
type IMsgSender interface {
Send(msg string) error
}

// EmailMsgSender 发送邮件
// 可能还有 电话、短信等各种实现
type EmailMsgSender struct {
emails []string
}

// NewEmailMsgSender NewEmailMsgSender
func NewEmailMsgSender(emails []string) *EmailMsgSender {
return &EmailMsgSender{emails: emails}
}

// Send Send
func (s *EmailMsgSender) Send(msg string) error {
// 这里去发送消息
return nil
}

// INotification 通知接口
type INotification interface {
Notify(msg string) error
}

// ErrorNotification 错误通知
// 后面可能还有 warning 各种级别
type ErrorNotification struct {
sender IMsgSender
}

// NewErrorNotification NewErrorNotification
func NewErrorNotification(sender IMsgSender) *ErrorNotification {
return &ErrorNotification{sender: sender}
}

// Notify 发送通知
func (n *ErrorNotification) Notify(msg string) error {
return n.sender.Send(msg)
}

单元测试

1
2
3
4
5
6
7
func TestErrorNotification_Notify(t *testing.T) {
sender := NewEmailMsgSender([]string{"test@test.com"})
n := NewErrorNotification(sender)
err := n.Notify("test msg")

assert.Nil(t, err)
}