本文介绍: 将不同职责的步骤进行串联,前一个执行完成之后才可以执行下一个,即前一个的责任完成之后会将这个责任给到下一个。

责任模式

简介

不同职责的步骤进行串联,前一个执行完成之后才可以执行下一个,即前一个的责任完成之后会将这个责任给到下一个。

组成结构

一共有两个主要的类

实现方式

class Handle {
  constructor () {
    this.handled = false
  }
  setNext (handle) {
    this.next = handle
    return this.next
  }
  deal (ctx) {
    // do something whit ctx
    if (!this.handled && this.next) {
      this.next.deal(ctx)
    }
    return true
  }
}

class HandleA extends Handle {
  deal (ctx) {
    // do something whit ctx
    ctx.handleA = true
    if (!this.handled && this.next) {
      this.next.deal(ctx)
    }
    return true
  }
}

class HandleB extends Handle {
  deal (ctx) {
    // do something whit ctx
    ctx.handleB = true
    if (!this.handled && this.next) {
      this.next.deal(ctx)
    }
    return true
  }
}

class HandleC extends Handle {
  deal (ctx) {
    // do something whit ctx
    ctx.handleC = true
    if (!this.handled && this.next) {
      this.next.deal(ctx)
    }
    return true
  }
}

const handlea = new HandleA()
handlea
  .setNext(new HandleB())
  .setNext(new HandleC())

const ctx = {}
handlea.deal(ctx)
console.log(ctx); // { handleA: true, handleB: true, handleC: true }

可以看到,由handled来决定是否当前处理节点终止,否则就会一直按照设置链路往下执行,这就是责任链的意义,你可以把他应用于http请求处理审批设计实现等等。。。

原文地址:https://blog.csdn.net/weixin_44863521/article/details/134241354

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_34198.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注