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");

本文介绍了一种常用的设计模式——责任链模式,并通过JavaScript代码实现了一个简单的例子。该模式允许请求沿着处理者链传递,直到有一个处理者处理它为止。文中详细展示了如何创建不同的处理者并设置它们之间的传递关系。
388

被折叠的 条评论
为什么被折叠?



