What?
http://en.wikipedia.org/wiki/Dependency_injection
Requirement
Implement this interface
In classes where dependency injection is wanted.
Code
Example
http://en.wikipedia.org/wiki/Dependency_injection
Requirement
Implement this interface
Wurst:
package DIObject
/**
* Implement this interface in your class so it can be injected
*/
public interface DIObject
Code
Wurst:
package DI
import HashMap
import DIObject
public class DI
private static DI instance = new DI
private HashMap<int, DIObject> dependencies = new HashMap<int, DIObject>
private construct()
skip
/**
*
* @returns DI
*/
static function getInstance() returns DI
return instance
/**
* Register a dependendency by a name
*
* @param string name
* @param DIObject dependency
*/
function set(string name, DIObject dependency)
dependencies.put(StringHash(name), dependency)
/**
* Gets a dependency by a name
*
* @param string name
* @returns DIObject|null
*/
function get(string name) returns DIObject
DIObject dependency = dependencies.get(StringHash(name))
if (dependency == null)
print("Dependency " + name + " is not registered")
return dependency
Example
Wurst:
package Example
import DI
import DIObject
// ----------------------------------------------------------------
// Interface
abstract class Implementation implements DIObject
abstract function greeting()
// ----------------------------------------------------------------
// Implementations
class ImplementationOne extends Implementation
override function greeting()
BJDebugMsg("Hi there")
class ImplementationTwo extends Implementation
override function greeting()
BJDebugMsg("I greet you")
// ----------------------------------------------------------------
init
DI.getInstance().set("implementation", new ImplementationOne)
DIObject dependency = DI.getInstance().get("implementation")
Implementation implementation = dependency castTo Implementation
implementation.greeting() // Hi there
// -----------------------------------------------------------
DI.getInstance().set("implementation", new ImplementationTwo)
dependency = DI.getInstance().get("implementation")
implementation = dependency castTo Implementation
implementation.greeting() // I greet you
Last edited: