可以用来消除请求的发送者和接收者之间的耦合,这是通过实现一个由隐式地对请求进行处理的对象组成的链而做到的。链中的每个对象可以处理请求,也可以将其传给下一个对象。JS内部就使用了这种模式来处一事件捕获和冒泡问题。一般的结构如下:
var Catalog = new Interface('Catalog', ['handleFilingRequest', 'findBooks','setSuccessor']);
var GenreCatalog = function() { // implements Catalog
this.successor = null;
this.catalog = [];
};
GenreCatalog.prototype = {
_bookMatchesCriteria:function(){},
handleFilingRequest: function(book) {
if(this._bookMatchesCriteria)//循环调用
this.successor.handleFilingRequest(book);
},
findBooks: function(request) {},
setSuccessor: function(successor) {
if(Interface.ensureImplements(successor, Catalog)){
this.successor = successor;
}
}
};
var SciFiCatalog = function() {}; // implements Catalog
extend(SciFiCatalog, GenreCatalog);
SciFiCatalog.prototype._bookMatchesCriteria = function(book) {
if(book.getTitle().match(/space/i)) {
return true;
}
return false;
};
var Library = new Interface('Library', ['addBook', 'findBooks', 'checkoutBook','returnBook']);
var PublicLibrary = function(books, firstGenreCatalog) { // implements Library
this.catalog = {};
this.firstGenreCatalog = firstGenreCatalog;
};
PublicLibrary.prototype = {
findBooks: function(searchString) {},
checkoutBook: function(book) { },
returnBook: function(book) {},
addBook: function(newBook) {
this.catalog[newBook.getIsbn()] = { book: newBook, available: true };
// 开始调用
this.firstGenreCatalog.handleFilingRequest(newBook);
}
};
// Instantiate the catalogs.
var biographyCatalog = new BiographyCatalog();
var fantasyCatalog = new FantasyCatalog();
var mysteryCatalog = new MysteryCatalog();
var sciFiCatalog = new SciFiCatalog();
// 组织责任链.
biographyCatalog.setSuccessor(fantasyCatalog);
fantasyCatalog.setSuccessor(mysteryCatalog);
mysteryCatalog.setSuccessor(nonFictionCatalog);
nonFictionCatalog.setSuccessor(sciFiCatalog);
// Give the first link in the chain as an argument to the constructor.
var myLibrary = new PublicLibrary(books, biographyCatalog);
使用这种模式可以把特定的具体类与客户隔离开,并代之以一条由弱耦合的对象组成的链。它将隐式的对请求进行处理。这有助于提高代码的模块化程度和可维护性。
这种模式有个缺点就是处理全是隐式的,所以不知道是否整个链走完了,或是是否被合理的处理了。所以需要程序员在不同的点给出确认。和双向观察者很类似。