Node.js之單利模式

在iOS中咱們常常用到單利模式,這樣就可以實如今多處共享同一數據,那麼在Node.js中也存在這種模式。node

咱們知道,Node.js中模塊的概念很重要,在寫模塊的接口的時候,只須要暴露出一個實例對象就能實現單利模式。git

這依賴於模塊加載的緩存機制,在這篇文章中我給出了說明。Node.js之循環依賴github

咱們先看看一個簡單的logger模塊的代碼:緩存

class Logger {
    constructor(name) {
        this.name = name;
        this.count = 0;
    }

    log(message) {
        this.count++;
        console.log(`${this.name} ${message} count: ${this.count}`);
    }

    info(message) {
        this.log(`info: ${message}`);
    }

    verbose(message) {
        this.log(`verbose: ${message}`);
    }
}

module.exports = new Logger("DEFAULT");

代碼很簡單,用的是ES6的新語法,這些其實都是prototype的語法糖。那麼再看看驗證是不是單利的代碼:less

const logger = require("./logger.js");
logger.info("This is a message");
logger.verbose("This is a verbose message");

打印結果:ui

DEFAULT info: This is a message count: 1
DEFAULT verbose: This is a verbose message count: 2

經過count屬性,咱們發現確實符合單利模式特性。this

以上這些內容來自於這本書nodejs-design-patternshttps://github.com/agelessman/MyBooksprototype

目前國內的資料仍是比較少的,像這麼好的書,確實值得推薦。code

相關文章
相關標籤/搜索