class Action { handle() { handle1 (); handle2 (); handle3 (); } handle1 () { console.log('1'); } handle2 () { console.log('2'); } handle3 () { console.log('3'); } }
Template Method pattern
: As above, if there is handle1 code, handle2, handle3 this process a few steps, then we can give up his package through a method call, then call this method can be used. For internal sequential method, a method can be encapsulated by, exposed to the outside.
Chain of Responsibility pattern: one step may be divided into multiple role responsibilities to complete. These roles separately and then together with a link chain. The originator and each handler isolation.
For example, you want to leave, need for approval, approval required leader, manager approval, final approval of Director
// leave approval, approval required leader, manager approval, final approval of director class Action { constructor(name) { this.name = name; this.nextAction = null; } setNextAction(action) { this.nextAction = action; } handle() { console.log(`${this.name} 审批`); if (this.nextAction != null) { this.nextAction.handle(); } } } // test the let A1 = new new the Action ( 'head' ); A2 the let = new new the Action ( 'manager' ); A3 the let = new new the Action ( 'director' ); a1.setNextAction(a2); a2.setNextAction (a3); a1.handle();
Application scenarios: promise.then chaining
Design Principles verification
Started in isolation each handler
Conforms to the Open Closed Principle