策略模式
根据类型选择不同的处理方式。
package main
import (
"fmt"
)
const (
NoteType = 0
TellphoneType = 1
)
type MessageNotify interface {
support(notifyType int) bool
notify(content string)
}
type Note struct {
}
func (n Note) support(notifyType int) bool {
return notifyType == NoteType
}
func (n Note) notify(content string) {
fmt.Printf("notify content: %s by note", content)
}
type Tellphone struct {
}
func (t Tellphone) support(notifyType int) bool {
return notifyType == TellphoneType
}
func (t Tellphone) notify(content string) {
fmt.Printf("notify content: %s by tellphone", content)
}
func sendMessage(notifyType int, content string, senders []MessageNotify) {
for _, sender := range senders {
if sender.support(notifyType) {
sender.notify(content)
}
}
}
func main() {
var n Note
var t Tellphone
senders := []MessageNotify{n, t}
sendMessage(1, "ok", senders)
}
输出
notify content: ok by tellphone
参考资料