Created
September 28, 2018 19:15
-
-
Save fluffybunnies/7a879a10d69dd9f6a808b7ef6e54d4e9 to your computer and use it in GitHub Desktop.
Factory + Inheritance
This file contains 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
'use strict'; | |
class ImportDaoInterface { | |
/** | |
This methods contract is x, y, z | |
*/ | |
getOrders(dateRange, cb) { | |
throw 'Extend Me!' | |
} | |
} | |
class GrubhubImportDao extends ImportDaoInterface { | |
getOrders(dateRange, cb) { | |
process.nextTick(function(){ | |
cb(false, []) | |
}) | |
} | |
} | |
function ImportDaoFactory(whichOne){ | |
//try { | |
// var importDao = new require('../dao/'+whichOne+'Dao') | |
//} catch (e) { | |
// throw new Error('Not Implemented') | |
//} | |
// the above for production, but for this all-in-one test case: | |
var importDao = new GrubhubImportDao | |
// can do factory things here if want to, like: | |
var getOrdersWrapper = importDao.getOrders | |
importDao.getOrders = function(dateRange,cb){ | |
getOrdersWrapper(dateRange,function(err,orders){ | |
if (err) { | |
console.log('report error to sentry, etc') | |
} | |
cb(err,orders) | |
}) | |
} | |
return importDao | |
} | |
// test... | |
ImportDaoFactory('GrubhubImport').getOrders('last 3 hours', function(err,orders){ | |
console.log('orders=',orders) | |
}) |
And can always add properties/attrs like:
function ImportDaoFactory(whichOne, props){
try {
var importDao = new (require('../dao/'+whichOne+'Dao')(props))
} catch (e) {
throw new Error('Not Implemented')
}
But I am against that cuz imho the instantiator should not know init values of a DAO/Adapter/whatever. That should be controlled by configs (or a separate class). It conflates responsibilities. Consider example where we leverage factory to cache instances and/or responses (to account for read slave lag)
I like the inheritance pattern with the caveat of:
- Dynamically loading classes based on a string at runtime
The second thing is that the ImportDaoFactory will be super repetitive. You should be able to abstract away what interface you define for the DAO and the autoloading of the class. I'll get a revised version of it in a sec
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thats really cool.