js责任链模式

原创
04/10 08:57
阅读数 20

如何优化if过多的问题,责任链模式是个好方法,责任链模式是一种行为型设计模式,其目的是建立一个对象链,将请求从链的一端传递到另一端,直到找到能够处理该请求的对象。使用责任链模式可以将请求发送者和具体请求处理者解耦,提高代码的灵活性和可维护性。下面是一个用JavaScript实现的简单的责任链模式示例:

// 定义一个基础处理器
class Handler {
  constructor() {
    this.next = null; // 下一个处理器
  }

  setNext(handler) {
    this.next = handler; // 设置下一个处理器
    return handler; // 返回下一个处理器,以支持链式调用
  }

  handle(request) {
    // 具体的处理逻辑由子类实现
    throw new Error('Method not implemented');
  }
}

// 具体处理器1,处理0-50的请求
class ConcreteHandler1 extends Handler {
  handle(request) {
    if (request >= 0 && request < 50) {
      console.log(`Request ${request} handled by ConcreteHandler1`);
    } else if (this.next) {
      this.next.handle(request); // 如果无法处理该请求,则交给下一个处理器处理
    } else {
      console.log(`All handlers cannot handle request ${request}`);
    }
  }
}

// 具体处理器2,处理50-100的请求
class ConcreteHandler2 extends Handler {
  handle(request) {
    if (request >= 50 && request < 100) {
      console.log(`Request ${request} handled by ConcreteHandler2`);
    } else if (this.next) {
      this.next.handle(request); // 如果无法处理该请求,则交给下一个处理器处理
    } else {
      console.log(`All handlers cannot handle request ${request}`);
    }
  }
}

// 具体处理器3,处理100-150的请求
class ConcreteHandler3 extends Handler {
  handle(request) {
    if (request >= 100 && request < 150) {
      console.log(`Request ${request} handled by ConcreteHandler3`);
    } else if (this.next) {
      this.next.handle(request); // 如果无法处理该请求,则交给下一个处理器处理
    } else {
      console.log(`All handlers cannot handle request ${request}`);
    }
  }
}

// 创建处理器链
const handler1 = new ConcreteHandler1();
const handler2 = new ConcreteHandler2();
const handler3 = new ConcreteHandler3();
handler1.setNext(handler2).setNext(handler3);

// 待处理的请求
const requests = [10, 80, 120, 200];

// 处理请求
requests.forEach(request => {
  handler1.handle(request);
});

在上面的代码中,我们定义了一个基础处理器类Handler,所有具体处理器都需要继承自该类并实现handle方法。具体处理器的handle方法中,首先判断自己能否处理该请求,如果能则处理完成;如果不能,则交给下一个处理器处理。如果所有的处理器都无法处理该请求,则输出错误信息。

最后,我们创建了一个处理器链,将所有的具体处理器串联起来,然后传入不同的请求进行处理。根据请求的不同,请求会被不同的处理器处理,或者无法得到处理。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部