github.com/szq-123/codingpractice@v0.0.0-20240430111904-2778dfaf7994/golang/coding/design_pattern/Chain.go (about)

     1  package design_pattern
     2  
     3  import (
     4  	"context"
     5  )
     6  
     7  /*
     8  职责链模式,Chain of responsibility
     9  常与composite一起使用,此时父构件作为对象的后继
    10  
    11  实现方式和应用较多,对于一个请求,可以灵活地注册若干个处理器
    12  1. 基于列表的方式,例如gorm,before_update, after_update 实现 或者 gin,handlers && c.Next 实现
    13  2. 每个对象保持对链上下个对象的引用
    14  */
    15  
    16  /*
    17  实现1,列表的形式
    18  */
    19  
    20  type HandlerChain struct {
    21  	ctx      context.Context
    22  	index    int
    23  	handlers []func(context.Context)
    24  }
    25  
    26  func (h *HandlerChain) Register(f func(context.Context)) {
    27  	h.handlers = append(h.handlers, f)
    28  }
    29  
    30  func (h *HandlerChain) Next() {
    31  	if h.index < len(h.handlers)-1 {
    32  		h.index++
    33  		h.handlers[h.index](h.ctx)
    34  	}
    35  }
    36  
    37  /*
    38  实现2,保持引用
    39  */
    40  
    41  type HandlerChain2 interface {
    42  	Handle(c context.Context)
    43  }
    44  
    45  type H1 struct {
    46  	Subsequence HandlerChain2
    47  }
    48  
    49  func (h *H1) Handle(c context.Context) {
    50  	if c.Value("H1 can handle").(string) == "true" {
    51  		return
    52  	}
    53  	h.Subsequence.Handle(c)
    54  }