Blog

Blog

PHODAL

MongoDB Nodejs构建CoAP物联网(二)——简单工厂模式

设计模式是一些有意思的东西,只是这些东西,只有在我们觉得代码写得很烂的时候才有用。比如,当我发现我在代码中重复写了很多个if来判断选择那个数据库的时候。于是,我就想着似乎这就可以用这个简单工厂模式来实现SQLite3与MongoDB的选择。

MongoDB Helper与SQLite Helper类重复

对于我们的类来说是下面这样子的:

function MongoDBHelper() {
    'use strict';
    return;
}

MongoDBHelper.deleteData = function (url, callback) {
    'use strict';
    ...    
};

MongoDBHelper.getData = function (url, callback) {
    'use strict';
    ...
};

MongoDBHelper.postData = function (block, callback) {
    'use strict';
    ...
};

MongoDBHelper.init = function () {
    'use strict';
    ...
};

module.exports = MongoDBHelper;

然而,我们可以发现的是,对于我们的SQLiteHelper来说也是类似的

SQLiteHelper.init = function () {
    'use strict';
    ...
};

SQLiteHelper.postData = function (block, callback) {
    'use strict';   
    ...
};

SQLiteHelper.deleteData = function (url, callback) {
    'use strict';
    ...
};

SQLiteHelper.getData = function (url, db_callback) {
    'use strict';
    ...
};

module.exports = SQLiteHelper;

想来想去觉得写一个父类似乎是没有多大意义的,于是用了简单工厂模式来解决这个问题。

简单工厂模式

从设计模式的类型上来说,简单工厂模式是属于创建型模式,又叫做静态工厂方法(Static Factory Method)模式,但不属于23种GOF设计模式之一。简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单实用的模式,可以理解为是不同工厂模式的一个特殊实现,学习了此模式可以为后面的很多中模式打下基础。

总之,就是我们可以用简单工厂模式来做一个DB Factory,于是便有了

var MongoDBHelper   = require("./mongodb_helper");
var SQLiteHelper    = require("./sqlite_helper");
var config          = require('../../iot').config;

function DB_Factory() {
    'use strict';
    return;
}

DB_Factory.prototype.DBClass = SQLiteHelper;

DB_Factory.prototype.selectDB = function () {
    'use strict';
    if (config.db === 'sqlite3') {
        this.DBClass = SQLiteHelper;
    } else if (config.db === "mongodb") {
        this.DBClass = MongoDBHelper;
    }
    return this.DBClass;
};

module.exports = DB_Factory;

这样我们在使用的时候,便可以:

var DB_Factory      = require("./lib/database/db_factory");

var db_factory = new DB_Factory();
var database = db_factory.selectDB();
database.init();

由于是直接由配置中读取进去的,这里的selectDB就不需要参数。

其他

CoAP物联网系统代码: https://github.com/gmszone/iot-coap

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签