职责链模式(Chain of Responsibility Pattern)
1 2 3 |
定义:为请求创建了一个接收者对象的链。 目的:避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。 场景:红楼梦中的"击鼓传花"。 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
// 采购请求 let PurchaseRequest = (amount, productName) => { this.amount = amount this.productName = productName } // 处理方 let Approver = (name, nextApprover) => { this.name = name this.nextApprover = nextApprover } Approver.prototype.processRequest = () => { throw new Error() } // ConcreteHandler let Manager = (name, nextApprover) => { Approver.call(this, name, nextApprover) } extend(Manager, Approver) Manager.prototype.processRequest = (request) => { if (request.Amount < 10000.0) { console.log('ok') } else if (NextApprover != null) { this.nextApprover.ProcessRequest(request) } } // ConcreteHandler,副总 let VicePresident = function (name, nextApprover) { Approver.call(this, name, nextApprover) } extend(VicePresident, Approver); VicePresident.prototype.processRequest = function (request) { if (request.Amount < 25000.0) { console.log('ok'); } else if (NextApprover != null) { this.nextApprover.ProcessRequest(request) } } // ConcreteHandler,总经理 let President = function (name, nextApprover) { Approver.call(this, name, nextApprover) } extend(President, Approver) President.prototype.processRequest = function (request) { if (request.Amount < 100000.0) { console.log('ok') } else if (NextApprover != null) { this.nextApprover.ProcessRequest(request) } } let requestTelphone = new PurchaseRequest(4000.0, "Telphone") let requestSoftware = new PurchaseRequest(10000.0, "Visual Studio") let requestComputers = new PurchaseRequest(40000.0, "Computers") let manager = new Manager("LearningHard") let Vp = new VicePresident("Tony") let Pre = new President("BossTom") // 设置责任链 manager.NextApprover = Vp Vp.NextApprover = Pre // 处理请求 manager.ProcessRequest(requestTelphone) manager.ProcessRequest(requestSoftware) manager.ProcessRequest(requestComputers) |