Node.JS 設(shè)計(jì)模式——行為模式

責(zé)任鏈模式 (Chain of Responsibility)


責(zé)任鏈模式的一個(gè)典型的NodeJS的例子就是Express中的Middleware模型。往往是一個(gè)請求或者數(shù)據(jù)對象需要經(jīng)過幾道工序或者需要從幾個(gè)handler中選擇一個(gè)handler來處理這個(gè)對象。每個(gè)工序會對這個(gè)對象就行判斷或者在這道工序上終止操作,要么會傳遞到下一個(gè)handler。所以這個(gè)設(shè)計(jì)模式,要求每個(gè)handler需要致命下一個(gè)handler是什么。然后每個(gè)handler需要有個(gè)判斷條件,來判斷是否需要傳遞到下一個(gè)handler還是在這個(gè)handler就終止。

class Handler1 (){
    constructor(next) {
        this.next = next;
    }
    
    judge(obj) {
       if (condition) {
            // do something
       } else if (this.next) {
           this.next.judge(obj);
       } else {
          // Error Handering
      }
    }
}

class Handler2 (){
    constructor(next) {
        this.next = next;
    }
    
    judge(obj) {
       if (condition) {
            // do something
       } else if (this.next) {
           this.next.judge(obj);
       } else {
          // Error Handering
      }
    }
}

handler2 = new Handler2(null);
handler1 = new Handler1(handler2);
handler1.judge(obj)

命令模式

image

命令模式,命令模式需要一個(gè)invoker來執(zhí)行不同的命令,所有的命令需要在invoker注冊。然后Client通過invoker來調(diào)用命令,然后在invoker里可以對所有的命令進(jìn)行一個(gè)記錄,就是history。然后就可以進(jìn)行undo或者redo的操作。每個(gè)命令基本上要有同樣的接口來指明命令的各種操作。操作名要一致。

  class command1 () {
      exec() {
      }
  }

  class command2 () {
    exec() {
    }
  }

  class invoker () {
      perform (name) {
        switch (name)
          case 'command1': 
              command1.exec()
               break;
           case 'command2': 
              command2.exec()
               break;
          default:
              error
      }
  }

策略模式

策略模式是針對同一件事情的不同做法,這點(diǎn)和命令模式的區(qū)別,命令模式是針對同一個(gè)對象的不同行為。所以這個(gè)模式往往是針對算法的封裝。


image
  class strategies() {
    static strategy1 () {
    }
    
    static strategy2() {
    }
  }
  modules.exports = strategies;

迭代器

迭代器模式的應(yīng)用場景就是需要經(jīng)常遍歷一個(gè)數(shù)據(jù)集合,但是我們數(shù)據(jù)集合的可能性很多,或者會變?;旧系骶褪且獙?shí)現(xiàn)first, last, next, hasNext 這些基本的函數(shù)。


  class iterator() {
    first() {
    }
    last() {
    }
    next() {
    }
    hasNext() {
    }
  }

觀察者模式

就是定義了一個(gè)一對多的關(guān)系,一但這個(gè)一得狀態(tài)發(fā)生改變,那么,其他的都要發(fā)生改變。


  class A () {
    constructor() {
      this.event = new EventEmitter();
    }
    change() {
        this.event.emit('change');
    }
  }
  class B () {
    constructor(event) {
      this.event = event;
    }
    observe() {
      this.event.on('change', () => {
      });
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容