Sample dependency injection for suburbanites
Posted: May 11, 2013 Filed under: Uncategorized Leave a commentProgrammers write a whole lot of code to use to “spin up” other objects in order to use that objects services and all of the required dependencies to use the object services are otherwise of absolutely no concern to the consumer of the service. It is pernicious. See Separation of concerns for more info.
The factory may seem like a lot of work and a lot of code but most times you don’t code it and it is generated, either at compile time, perhaps using attributes for some aspect oriented programming, or at runtime using reflection. In the end whatever work you put into configuring it is supposed to be recouped by all the supposedly many consumers who no longer have to open their garage door and rummage about for two stroke oil.
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
| // All I want is my lawn mowed. | |
| // Yet I have to gather up the tools which are of no direct use to me in this case. | |
| var myLawn = {}, myWalk = {}; | |
| var myTools = MyGarage.Tools(["mower", "gas", "oil", "broom"]); | |
| var gardener = new Gardener(myTools); | |
| gardener.mow(myLawn); | |
| //Given the factory code below now all I have to do is this. | |
| var worker = workerFactory().getWorker("gardener") | |
| worker.mow(myLawn); | |
| worker.sweep(myWalk); | |
| var workerFactory = function() { | |
| map = { | |
| gardener : { | |
| tools : ["mower", "gas", "oil", "broom"], | |
| skills : {mow: function(lawn) {return "yes boss";}, sweep: function(walk) {return "yes boss";}} | |
| } | |
| } | |
| function getWorker(type) { | |
| var worker = {type: type}; | |
| // Give the worker tools | |
| var tools = map[type].tools; | |
| worker.tools = []; | |
| for (var item in tools) { | |
| worker.tools[item] = tools[item]; | |
| } | |
| // Give the worker skills | |
| var skills = map[type].skills; | |
| for (var item in skills) { | |
| worker[item] = skills[item]; | |
| } | |
| return worker; | |
| } | |
| return { | |
| getWorker: getWorker | |
| } | |
| } |