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

责任模式

简介

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

组成结构

一共有两个主要的类

实现方式

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请求处理审批设计实现等等。。。

发表回复

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