带优先级的责任链设计模式应用

责任链设计模式

责任链设计模式的典型场景:

  • 一个对象或请求,需要验证一系列的判断,依次执行,顺序不限;核心目的:用于解耦发送方和处理方

带优先级的责任链设计模式:

  • 某些情况下,责任链Handler需要有先后顺序执行

实现

  • ConcreteHandler嵌套BaseHandler,间接实现 BaseHandler的 方法SetNext、HandleNext、Priority

  • 同时ConcreteHandler实现业务Handle方法

  • ByPriority,实现了sort方法的所有方法,实现sort.Sort接口要求

go 复制代码
type Handler interface {
    SetNext(handler Handler)
    Handle(currentValue, PreviousValue float64) (handled bool)
    Priority() int
}

type BaseHandler struct {
    next     Handler
    priority int // 处理器的优先级
}

func (h *BaseHandler) SetNext(handler Handler) {
    h.next = handler
}

func (h *BaseHandler) HandleNext(currentValue, PreviousValue float64) (handled bool) {
    if h.next != nil {
        return h.next.Handle(currentValue, PreviousValue)
    }
    return false
}

func (h *BaseHandler) Priority() int {
    return h.priority
}

type ConcreteHandler struct {
    BaseHandler
    handleFunc func(currentValue, PreviousValue float64) bool // 处理函数
}

func (h *ConcreteHandler) Handle(currentValue, PreviousValue float64) (handled bool) {
    // 如果 handleFunc 处理请求的结果为(返回 true),则停止处理
    if h.handleFunc(currentValue, PreviousValue) {
        return false
    }
    // 否则,传递给下一个处理器
    return h.HandleNext(currentValue, PreviousValue)
}

func NewConcreteHandler(priority int, handleFunc func(currentValue, PreviousValue float64) bool) Handler {
    return &ConcreteHandler{
        BaseHandler: BaseHandler{priority: priority},
        handleFunc:  handleFunc,
    }
}

type ByPriority []Handler

func (a ByPriority) Len() int      { return len(a) }
func (a ByPriority) Swap(i, j int) { a[i], a[j] = a[j], a[i] }

// 1==>优先级最大
func (a ByPriority) Less(i, j int) bool { return a[i].Priority() < a[j].Priority() }

业务逻辑,实现Handler

  • 通过NewConcreteHandler,构建业务Handler,返回业务处理结果;true则不再往下执行
go 复制代码
handlers := []Handler{
        NewConcreteHandler(1, func(_currentValue, _PreviousValue float64) bool {

            pRule := ConstructExpression(PriorityRules)
            expr, _ := govaluate.NewEvaluableExpression(pRule)

            con := make(map[string]interface{})
            con[ExpressionCurrentKey] = _currentValue
            con[ExpressionPreviousValueKey] = _PreviousValue

            result, _ := expr.Evaluate(con)
            if result.(bool) {
                fmt.Printf("当前值%v 前值%v 结果%v 触发表达式:%v\n",
                    con[ExpressionCurrentKey], con[ExpressionPreviousValueKey], result, pRule)
            }

            return result.(bool)

        }),
        NewConcreteHandler(2, func(_currentValue, _PreviousValue float64) bool {

            rule := ConstructExpression(Rules)
            expr, _ := govaluate.NewEvaluableExpression(rule)

            con := make(map[string]interface{})
            con[ExpressionCurrentKey] = _currentValue
            con[ExpressionPreviousValueKey] = _PreviousValue

            result, _ := expr.Evaluate(con)
            if result.(bool) {
                fmt.Printf("当前值%v 前值%v 结果%v 触发表达式:%v\n",
                    con[ExpressionCurrentKey], con[ExpressionPreviousValueKey], result, rule)
            }
            return result.(bool)
        }),
    }

构建链以及调用

  • 根据场景,可以构建多个Handler,并根据优先级执行排序并依次执行SetNext方法,使得对象可以经由多个逻辑依次处理,直至处理结束,实现责任链的执行。
go 复制代码
 sort.Sort(ByPriority(handlers))

    for i := 0; i < len(handlers)-1; i++ {
        handlers[i].SetNext(handlers[i+1])
    }

    for _, handler := range handlers {

        if !handler.Handle(currentValue.Value, *alertRule.PreviousValue) {
            // break
            return true, nil
        }
    }
    return false, nil

效果验证

相关推荐
张先shen12 分钟前
Spring Boot集成Redis:从配置到实战的完整指南
spring boot·redis·后端
Dolphin_海豚16 分钟前
一文理清 node.js 模块查找策略
javascript·后端·前端工程化
极光雨雨1 小时前
【设计模式】单例模式 饿汉式单例与懒汉式单例
单例模式·设计模式
EyeDropLyq1 小时前
线上事故处理记录
后端·架构
MarkGosling4 小时前
【开源项目】网络诊断告别命令行!NetSonar:开源多协议网络诊断利器
运维·后端·自动化运维
Codebee4 小时前
OneCode3.0 VFS分布式文件管理API速查手册
后端·架构·开源
_新一4 小时前
Go 调度器(二):一个线程的执行流程
后端
estarlee4 小时前
腾讯云轻量服务器创建镜像免费API接口教程
后端
风流 少年4 小时前
Cursor创建Spring Boot项目
java·spring boot·后端
毕设源码_钟学姐5 小时前
计算机毕业设计springboot宿舍管理信息系统 基于Spring Boot的高校宿舍管理平台设计与实现 Spring Boot框架下的宿舍管理系统开发
spring boot·后端·课程设计