Chain of Responsibility模式参考图片:
代码:
var Handler = function() {};
Handler.prototype.getSuccessor = function() {
return this.successor;
};
Handler.prototype.setSuccessor = function(o) {
this.successor = o;
};
Handler.prototype.handlerRequest = function(request) {
if (this.successor != null)
this.successor.handlerRequest(request);
else
console.log("the end");
};
var ConcreteHandler1 = function(o) {
this.setSuccessor(o);
ISuper = {
handlerRequest: this.handlerRequest
};
this.handlerRequest = function(request) {
console.log("ConcreteHandler1 operation");
if (request.indexOf("key1") >= 0) {
console.log("is me");
return;
}
ISuper.handlerRequest.call(this, request);
};
};
ConcreteHandler1.prototype = new Handler;
ConcreteHandler1.prototype.constructor = ConcreteHandler1;
var ConcreteHandler2 = function(o) {
this.setSuccessor(o);
ISuper = {
handlerRequest: this.handlerRequest
};
this.handlerRequest = function(request) {
console.log("ConcreteHandler2 operation");
if (request.indexOf("key2") >= 0) {
console.log("is me");
return;
}
ISuper.handlerRequest.call(this, request);
};
};
ConcreteHandler2.prototype = new Handler;
ConcreteHandler2.prototype.constructor = ConcreteHandler2;
var ConcreteHandler3 = function(o) {
this.setSuccessor(o);
ISuper = {
handlerRequest: this.handlerRequest
};
this.handlerRequest = function(request) {
console.log("ConcreteHandler3 operation");
if (request.indexOf("key3") >= 0) {
console.log("is me");
return;
}
ISuper.handlerRequest.call(this, request);
};
};
ConcreteHandler3.prototype = new Handler;
ConcreteHandler3.prototype.constructor = ConcreteHandler3;
var o = new ConcreteHandler3(new ConcreteHandler2(new ConcreteHandler1()));
o.handlerRequest("key2");