Javascinating

October 31, 2009

Dependency Injection Explained in 2 Minutes

Filed under: Software Development — Gary P. Russell @ 8:22 pm

Bad – MyBar is tightly coupled to MyFoo

public class MyFoo{
    public void someMethod() {
         ...
    }
}

public class MyBar {
    private MyFoo foo = new MyFoo;
}

Good – MyBar refers to the interface Foo; to change to a different implementation you only have to change where MyFoo is instantiated.

public interface Foo{
    public void someMethod();
}

public class MyFoo implements Foo{
    public void someMethod() {
         ...
    }
}

public class MyBar {
    private Foo foo = new MyFoo();
}

Better – MyBar refers to interface Foo and gets the implementation by calling a factory; the factory decides which implementation of Foo to return.

public interface Foo{
    public void someMethod();
}

public class MyFoo implements Foo{
    public void someMethod() {
         ...
    }
}

public class MyFooFactory {
    public static Foo getInstance() {
        return new MyFoo();
    }
}

public class MyBar {
    private Foo foo = FooFactory.getInstance();
}

The getInstance() method can take, say, a Properties parameter so the client can supply attributes about what kind of Foo he wants.

Best – MyBar refers to interface Foo and has no direct involvement as to exactly which implementation of Foo is supplied; the instance is “injected” into MyBar; in this case, in the constructor.

public interface Foo{
    public void someMethod();
}

public class MyFoo implements Foo{
    public void someMethod() {
         ...
    }
}

public class MyBar {
    private Foo foo;

    public MyBar(Foo foo) {
        this.foo = foo;
    }
}

I clearly have a bias, but the Spring Framework provides an excellent method for injecting dependencies.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress