首页 > IT职业 > IT图书 > 从TJ大神源码中学习代理模式
我们知道koa中有个context对象,context表示请求的上下文。今天在看这段代码的时候,发现了tjgit自己写的一个代理模式,觉得不错,记录一下。
地址:[delegates源码]https://github.com/tj/node-delegates/blob/master/index.js
设计模式中的代理模式是什么意思呢?
代理可以简单理解为:
context其实是response和request的代理,将两者的一些方法注册到context上,这样通过context就可以访问到请求的上下文。
看看源码:
function Delegator(proto, target) { // 这样写是为了兼容直接调用delegate(proto, 'response')
// 这样也能返回一个对象
if (!(this instanceof Delegator)) return new Delegator(proto, target); // 工厂模式注册各种方法
this.proto = proto; this.target = target; this.methods = []; this.getters = []; this.setters = []; this.fluents = [];
}
Delegator.prototype.method = function(name){ var proto = this.proto; var target = this.target; this.methods.push(name);
proto[name] = function(){ // 通过apply将this绑定到原对象,使用当前参数
return this[target][name].apply(this[target], arguments);
}; return this;
};
getter和setter:
Delegator.prototype.getter = function(name){ var proto = this.proto; var target = this.target; this.getters.push(name);
proto.__defineGetter__(name, function(){ return this[target][name];
}); return this;
};
Delegator.prototype.setter = function(name){ var proto = this.proto; var target = this.target; this.setters.push(name);
proto.__defineSetter__(name, function(val){ return this[target][name] = val;
}); return this;
};
用法:
delegate(proto, 'response')
.method('attachment')
.method('redirect')
.method('remove')
.method('vary')
.method('set')
.method('append')
.method('flushHeaders')
作者:陈小俊先生
链接:https://www.jianshu.com/p/7f2f45f9e6c9
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/615/viewspace-2812539/ ,如需转载,请注明出处,否则将追究法律责任。