标签:复用 return roo nil handle 执行顺序 做事 str next
type Handler interface {
do()
SetNext(handler Handler) Handler
Run()
}
// 用以复用
type Next struct {
nextHandler Handler
}
func (n *Next) SetNext(handler Handler) Handler {
n.nextHandler = handler
return handler
}
func (n *Next) Run() {
if n.nextHandler != nil {
n.nextHandler.do()
n.nextHandler.Run()
}
}
// RootHandler do nothing
type RootHandler struct {
Next
}
// 根结点不做事
func (h RootHandler) do() {
// do nothing
}
type OneHandler struct {
Next
}
func (o OneHandler) do() {
fmt.Println("handler one do something")
}
type TwoHandler struct {
Next
}
func (o TwoHandler) do() {
fmt.Println("handler two do something")
}
root := &RootHandler{}
// 执行顺序一目了然
root.SetNext(&TwoHandler{}).
SetNext(&OneHandler{})
root.Run()
标签:复用 return roo nil handle 执行顺序 做事 str next
原文地址:https://www.cnblogs.com/asketch/p/14488965.html