Created
May 5, 2016 14:03
-
-
Save leemason/cdf80455d205bebc71574a1e68a46cbd to your computer and use it in GitHub Desktop.
Factory/Service Locator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let factory = require('factory'), | |
db = require('db_module'), | |
config = require('config'); | |
factory.register('db', function(){ | |
return new db(config.db); | |
}); | |
//carry on, db is registered |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let factory = require('factory'), | |
DB = factory.get('db'); | |
// Now you can use DB as its already created via the factory, this means we dont need to create it everywhere we use it. | |
export default class Controller{ | |
postIndex(req, res){ | |
//or get here | |
let DB = factory.get('db'); | |
DB.insert('table', req.get('data')); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Factory{ | |
get(key){ | |
//if created return the instance | |
if(this.created(key)){ | |
return this.created[key]; | |
} | |
//if registered invoke, store and return | |
if(this.has(key)){ | |
return this.create(key); | |
} | |
//throw error | |
throw new Error('not registered'); | |
} | |
register(key, cb){ | |
this.items[key] = cb; | |
} | |
//internal helper methods refrenced above.... | |
} | |
export default new Factory(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment