编辑:删除了更高层次的想法,包括特定问题和不易迁移的代码。
我使用 DAO 实现了我的 DAL。我的应用程序连接到各种数据库(主要是出于遗留原因)。为了促进高效和智能地使用连接,我使用ConnectionBroker
单例来管理可能(或可能不)打开的各种连接。然后ConnectionBroker
将其注入到 DAO 中,在那里他们可以请求对特定连接对象的控制、请求新连接等。
从继承 POV,我想要类似的东西:
AbstractDbConnection
|-- MongoDbConnection
|-- MsSqlConnection
|-- CouchDbConnection
|-- ...
WhereAbstractDbConnection
定义了一个接口,并实现了一些共享的基于事件的逻辑。
var EventEmitter = require('events').EventEmitter;
module.exports = function AbstractDbConnection(host, port, database, login, ...) {
// private
var state = StatesEnum.Closed; // StatesEnum = {Open: 0, Closed: 1, ..}; Object.freeze(StatesEnum);
// api that must be overwritten
this.connect = function connect() {throw new ...}
this.disconnect = function disconnect() {throw new ...}
... <more>
this.getState = function() { return state; }
}
AbstractDbConnection.prototype.__proto__ = EventEmitter.prototype;
然后我使用特定于驱动程序的代码实现接口:
var mssqldriver = require('mssqldriver'), //fictitious driver
AbstractDbConnection = require(__dirname + '/blah/AbstractDbConnection');
module.exports = function MsSqlConnection(host, port, database, login, ...) {
var me = this;
// implement using driver
this.connect = function connect() {...}
this.disconnect = function disconnect() {...}
... <more>
driverSpecificConnection.on('driverSpecificOpenEvent', function() {
me.emit('open'); // relay driver-specific events into common events
state = StatesEnum.Open; // how ??
}
...
}
MsSqlConnection.prototype.__proto__ = new AbstractDbConnection();
但显然我想保护state
财产不被无意改变。