策略模式

根据类型选择不同的处理方式。

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

参考资料

https://juejin.cn/post/7183349759569035324#heading-23

posted on 2023-08-20 14:41  王景迁  阅读(3)  评论(0编辑  收藏  举报

导航