责任链模式是一种行为设计模式,它让你可以将请求沿着处理者链进行发送。收到请求后,每个处理者都可以处理请求,或者将其传递给链上的下一个处理者。
type Handler interface {
execute(pms *Pms) error
setNext(Handler)
}
type handlerA struct {
next Handler
}
func (h *handlerA) execute(pms *Pms) error {
if pms.isLogin {
return h.next.execute(pms)
}
return fmt.Errorf("not login")
}
func (h *handlerA) setNext(next Handler) {
h.next = next
}
type handlerB struct {
next Handler
}
func (h *handlerB) execute(pms *Pms) error {
if pms.isPay {
return h.next.execute(pms)
}
return fmt.Errorf("not pay")
}
func (h *handlerB) setNext(next Handler) {
h.next = next
}
type handlerC struct {
next Handler
}
func (h *handlerC) execute(pms *Pms) error {
if pms.isFh {
if h.next == nil {
fmt.Println("fh success")
return nil
} else {
return h.next.execute(pms)
}
}
return fmt.Errorf("not fh")
}
func (h *handlerC) setNext(next Handler) {
h.next = next
}
type Pms struct {
name string
isLogin bool
isPay bool
isFh bool
}
func ExecuteReponsibility() {
pms := &Pms{
name: "test",
isLogin: true,
isPay: true,
isFh: true,
}
handlerA := &handlerA{}
handlerB := &handlerB{}
handlerC := &handlerC{}
handlerA.setNext(handlerB)
handlerB.setNext(handlerC)
handlerA.execute(pms)
}