Anyway, I've heard about Dependency Injections a lot lately, and I finally decided to research what it's about. Wow, I never realized how simple a concept it would be. Having been exposed to different design patterns like Factory Method, this was extremely easy to assimilate.
Dependency Injection works very well with Flex interfaces, and particularly well with Factories. If I have an object A which depends on object B, I could have A instantiate B and maintain a reference to it. Unfortunately, this creates a dependency within A upon B:
private var bInstance:B;
...
bInstance = new B();
bInstance.foo();
In this case, A has a definite dependency upon B's implementation. If B changes 'foo()' to anything else, A will break.
We can partially solve this via a interface, in which A and B agree on B's required methods. In this case, B utilizes an interface, BI, which instructs B to always implement 'foo()'. Thus, A can access B via its instance:
private var bInstance:BI;
...
bInstance = new B();
bInstance.foo(); //guaranteed since bInstance is an instance of type BI
But we still have a problem: A is still relying on the base class of B. What if we wanted to break B into different objects, and 'B' was no longer a valid name? Moreover, what if we moved B to a different library? Enter a factory.
Rather than A creating B, even via its interface, what if the code calling A passed in a reference to B, via its interface? For this, we'll add two new classes. 'Factory' has a 'createBI' function that returns a reference to B via its interface, BI. FooBar is a class which creates A. In this class, the code to create A might look something like this:
a = new A(Factory.createBI());
Whereas the constructor for A might look like this:
private bInst:BI;
public function A(bInst:BI):void {
this.bInst = bInst;
}
From this point, we've broken the dependency of A to B, and created a new dependency from A to BI. This is a better design and is more extensible: should we need to have different variations of B, as long as they implement the BI interface, A can utilize them.
What's more, 'FooBar' injected the dependencies into A.
That's all there is to it.
Now...my question is...how far can you take this??
No comments:
Post a Comment