下面这行代码仔细一想,和把业务逻辑抽离成方法,然后一个一个掉方法本质是一样的,但是区别在于我们在中间件注册的方法不应该是业务逻辑,而应该是脱离于业务逻辑提供的一种适用于大多数场景的一个方法,她所提供的功能应该具有单一性 普适性
function Middleware(){
this.cache = [];
}
Middleware.prototype.use = function(fn){
if(typeof fn !== 'function'){
throw 'middleware must be a function';
}
this.cache.push(fn);
return this;
}
Middleware.prototype.next = function(){
if(this.middlewares && this.middlewares.length > 0 ){
var ware = this.middlewares.shift();
ware.call(this, this.next.bind(this));
}
}
Middleware.prototype.handleRequest = function(){//执行请求
this.middlewares = this.cache.map(function(fn){//复制
return fn;
});
this.next();
}
var middleware = new Middleware();
middleware.use(function(next){
console.log(1);
next();
console.log('1结束');
});
middleware.use(function(next){
console.log(2);
next();
console.log('2结束');
});
middleware.use(function(next){
console.log(3);
console.log('3结束');
});
middleware.use(function(next){
console.log(4);next();console.log('4结束');
});
middleware.handleRequest();