nodejs 做中间件
在软件领域,中间件是在应用与应用之间充当连接服务的,这并非是nodejs的概念,其他领域也会有这个概念。
举个例子,比如消息队列、数据库驱动等。 插件一般来说extra的,就是你整个系统或应用不需要插件也能正常工作,插件一般是提供一些额外功能。而且插件这个词本身代表的就是可拓展的(形象的说,可插拔)。 我个人认为 plugin/addon = extra feature 模块一般是系统的负责某一功能的一部分,不可或缺。即 module = a part of system/application
在 nodejs 里一般你在 package.json 里指定的那些package 都是 module,当然你从文件名 node_modules 也能看出来
把大象放入冰箱的过程是这样的:
function play_with_elephant (){
open();// 打开门
in_elephant();// 放入大象
close();// 关上门return result;}
那么如果这样写:
function play_with_elephant (action_elephant){
open();// 打开门
action_elephant();// 捣鼓大象
close();// 关上门return result;}
action_elephant 就可以看作是play_with_elephant的一个中间件,ta运行在一套算法的中间,属于可变动的内容。
当然,在纯OO语言中
Class P {...void play_with_elephant (action){
open();// 打开门
action.action_elephant();// 捣鼓大象
close();// 关上门 }}
还会看到又臭又长的抽象工厂来包装:
function createPlay (factory){var action = factory.creaeAction();var door = factory.createDoor();
door.open();
action.action_elephant();
door.close();}
当然了,加上管理
function W (){this.stack =[];}
W.prototype.use=function(f){this.stack.push(f);};
W.prototype.play_with_elephant =function(){
play_with_elephant(function(){this.stack.forEach(function(f){
f();});});};
balabala...function play_with_elephant (action_elephant){
open();// 打开门
action_elephant();// 捣鼓大象
close();// 关上门return result;}

浙公网安备 33010602011771号