Skip to content

Instantly share code, notes, and snippets.

@domenic
Created April 17, 2012 00:20
Show Gist options
  • Save domenic/2402514 to your computer and use it in GitHub Desktop.
Save domenic/2402514 to your computer and use it in GitHub Desktop.
StackOverflow DI example
public class A
{
private Bable b;
private Cable c;
public A(Bable b, Cable c)
{
this.b = b;
this.c = c;
}
public void doThings() {
this.b.doBThings();
this.c.doCThings();
}
}
public interface Bable
{
public void doBThings();
}
public interface Cable
{
public void doCThings();
}
public interface Xable
{
public void doXThings();
}
public class B implements Bable
{
private Xable x;
// You said B depends on C
// I am betting B does not depend on the same aspect of C
// that A does, so I am separating those aspects out into
// the Cable interface (for A) and the Xable interface (for B).
// The concrete C class happens to implement both, but B only
// cares about the Xable contract, whereas A only cares about
// the Cable contract.
public B(Xable x)
{
this.x = x;
}
public void doBThings()
{
// TODO: do something B-specific
// also use the Xable contract
this.x.doXThings();
}
}
public class C implements Cable, Xable
{
public void doCThings() {}
public void doXThings() {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment