继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

从TJ大神源码中学习代理模式

RISEBY
关注TA
已关注
手记 309
粉丝 70
获赞 317

我们知道koa中有个context对象,context表示请求的上下文。今天在看这段代码的时候,发现了tjgit自己写的一个代理模式,觉得不错,记录一下。

地址:[delegates源码]https://github.com/tj/node-delegates/blob/master/index.js

设计模式中的代理模式是什么意思呢?

代理可以简单理解为:

为其他对象提供一种代理以控制对这个对象的访问。

context其实是responserequest的代理,将两者的一些方法注册到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 = [];
}

method方法

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')

tj代码,就是程序员的教科书



作者:陈小俊先生
链接:https://www.jianshu.com/p/7f2f45f9e6c9


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP