一个请求(数据),请求先经过A处理器处理,然后再把请求传递给B处理器,B处理完在往C传,以此类推,链条上的每个处理器 各自承担各自的处理职责

定金返优惠券

公司针对支付过定金的用户有一定的优惠政策,在正式购买后已经支付过100定金的返50优惠券,已经支付200的返100优惠券!没有支付定金正常购买的没有优惠券!

  1. class TaskChain {
  2. //target:目标任务
  3. constructor(target,data) {
  4. this.data = data || {};
  5. this.target = target
  6. this.index = 0
  7. this.interceptorSize = 0
  8. this.interceptors = []
  9. }
  10. //添加拦截器
  11. addInterceptor(interceptor) {
  12. this.interceptors.push(interceptor)
  13. this.interceptorSize++
  14. return this
  15. }
  16. //执行任务
  17. start() {
  18. this.index = 0
  19. this.next()
  20. }
  21. //继续执行
  22. next() {
  23. if (this.index < this.interceptorSize) {
  24. this.interceptors[this.index++](this.data, this.next.bind(this))
  25. return
  26. }
  27. if (this.target) {
  28. this.target()
  29. }
  30. }
  31. }
  32. function order100({ orderType, payStatus }, next){
  33. console.log('order100')
  34. if( orderType === '100' && payStatus ){
  35. return console.log('100预约金、得到50优惠券')
  36. }
  37. next()
  38. }
  39. function order200({ orderType, payStatus }, next){
  40. console.log('order200')
  41. if( orderType === '200' && payStatus ){
  42. return console.log('200预约金、得到100优惠券')
  43. }
  44. next()
  45. }
  46. let taskChain = new TaskChain(() =>{
  47. console.log('责任链结束')
  48. });
  49. taskChain.addInterceptor(order100)
  50. taskChain.addInterceptor(order200)
  51. taskChain.start()


总结

优点

  • 解耦:发送者和接收者解耦,接收者是请求的处理者
  • 动态组合:可以动态的组合责任链的顺序、随时增加拆除责任链中的某个请求对象

    缺点

  • 如果责任链太长,或者请求的处理时间过长可能会影响性能

  • 责任链个数多