Node.js与单例模式

1、前端的JavaScript单例模式

单例模式是非常常用的设计模式,前端的JavaScript中单例模式代码可能 如下所示:

var GameManager = (function () {
    var singleton;
    function Construct() {
        //定义一些属性
        this.grid_x = 18;//x网格数量
        this.grid_y = 11;//y网格数量
        this.grideSize = 100;//网格大小
        this.xOffset = 40;// 场景偏移量
        this.yOffset = 40;// 场景偏移量
        this.playing = true;
        this.starMapArray = [];
        //。。。    
    }
    singleton = new Construct();
    return singleton;
})();

/**定义一些方法 */
GameManager.someFunction = function () {
        console.log("Hello World");
}

是的,正如你看到的,单例对象的方法属性定义时是不需要prototype关键字的;在使用该对象时,在需要的地方直接调用即可:

GameManager.someFunction();



2、Node.js的单例模式

总所都知,Node.js中是用module.exports来管理模块的;
假设有这样一个DealManager 模块 (文件为DealManager .js):

var DealManager = function () {};
DealManager.prototype.init = function () {
    console.log('hello world');
};

module.exports = DealManager;

这个模块在node.js中的使用通常是这样的:

var dealManager = require('./managers/DealManager');
...
var myDealManager = new dealManager();
myDealManager.init();

代码中可以定义多个dealManager实例对象;

因为module.exports本身是单例的;所以,在Node.js中创建单例模块比前端更容易一些,下面是DealManager在Node.js中的单例写法(DealManager_Singleton .js):

var DealManager = function () {};

module.exports.init = function () {
    console.log('hello world');
};

module.exports.DealManager = DealManager;

module.exports.DealManager表示给module.exports添加了一个属性;
module.exports.init 表示在这个模块的作用域内(DealManager_Singleton .js)添加一个init方法;这样,就产生了一个包含init方法的单例的DealManager对象了;

如果这时候,继续使用前面的调用方式,将得到一个错误提示:

var myDealManager = new dealManager();
                    ^

TypeError: dealManager is not a constructor
    at Object.<anonymous> (D:\nodejs\server\app.js:39:21)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)

这时候,dealManager已经不能使用new 方法了;它的正确的使用方法如下:

var dealManager = require('./managers/DealManager_Singleton');
dealManager.init();

这时的运行结果如下:

D:\nodejs\server\>node app.js
hello world

app.js代码就不列出了,相信你看这篇文章的时候,已经知道怎么创建和运行一个可以输出"hello world"的app.js的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。