學習設計模式——職責鏈模式

職責鏈模式

 // 定義一個公共類
    let Leader = function () {
      this.nextLeader = null;
    };
    Leader.prototype.setNext = function (next) {
      this.nextLeader = next;
      return next; // 這樣可以鏈式子調用
    }

    // 定義職責鏈的節點
    let GroupLeader = new Leader();
    GroupLeader.handle = function (duration) {
      if (duration <= 0.5) {
        console.log('<=0.5天 小組領導可以批,批准了')
      } else {
        this.nextLeader.handle(duration)
      }
    }

    let DepartmentLeader = new Leader();
    DepartmentLeader.handle = function (duration) {
      if (duration <= 1) {
        console.log('<=1天 部門領導可以批,批准了')
      } else {
        this.nextLeader.handle(duration)
      }
    }

    let GeneralLeader = new Leader();
    GeneralLeader.handle = function (duration) {
      if (duration <= 2) {
        console.log('<=2天 總經理可以批,批准了')
      } else {
        console.log('想離職是吧?')
      }
    }

    // 排列職責鏈
    // GroupLeader.setNext(DepartmentLeader)
    // DepartmentLeader.setNext(GeneralLeader)
    GroupLeader.setNext(DepartmentLeader).setNext(GeneralLeader)

    // 執行場景,請假,組長批不了,遞交給上一級部門領導,部門領導批不了遞交給上一級總經理
    GroupLeader.handle(0.5)
    GroupLeader.handle(1)
    GroupLeader.handle(2)
    GroupLeader.handle(3)

    // ES6
    // 領導基類
    class Leader2 {
      constructor() {
        this.nextLeader = null;
      }
      setNext(next) {
        this.nextLeader = next
        return next;
      }
    }

    class GroupLeader2 extends Leader2 {
      handle(duration) {
        if (duration <= 0.5) {
          console.log('<=0.5天 小組領導可以批,批准了')
        } else {
          this.nextLeader.handle(duration)
        }
      }
    }

    class DepartmentLeader2 extends Leader2 {
      handle(duration) {
        if (duration <= 1) {
          console.log('<=1天 部門領導可以批,批准了')
        } else {
          this.nextLeader.handle(duration)
        }
      }
    }

    class GeneralLeader2 extends Leader2 {
      handle(duration) {
        if (duration <= 2) {
          console.log('<=2天 總經理可以批,批准了')
        } else {
          console.log('想離職是吧?')
        }
      }
    }

    const ZhangSan = new GroupLeader2()
    const LiSi = new DepartmentLeader2()
    const WangWu = new GeneralLeader2()

    ZhangSan.setNext(LiSi).setNext(WangWu)
    ZhangSan.handle(0.5) //  小組領導經過一番心理鬥爭:批准了
    ZhangSan.handle(1) //  部門領導經過一番心理鬥爭:批准了
    ZhangSan.handle(2) //  總經理經過一番心理鬥爭:批准了
    ZhangSan.handle(3) //  總經理:不準請這麼長的假
發佈了163 篇原創文章 · 獲贊 99 · 訪問量 69萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章