Reputation: 849
I have three major classes, lets say A, B and C. A instantiates both B and C. B also depends on C. B accesses C's object through setter/getter methods. This is fine. My problem is that A's implementation is tightly coupled with B's and C's implementation. I want to decouple this. I don't want to use the spring framework. Is there any other way? I thought of creating factories for their(B,C) initialization s but that means whenever A or C will need to access B they have to create a new instance of the Factory again.. this doesn't seem right. How should I solve this? I am not sure if the IOC container is useful here?
Upvotes: 0
Views: 152
Reputation: 112927
A
should not directly instantiate B
or C
. It should instead accept instances of them as constructor parameters:
public class A
{
private B b;
private C c;
public A(B b, C c)
{
this.b = b;
this.c = c;
}
}
// When creating your object graph, in the "composition root":
B b = new B();
C c = new C(b);
A a = new A(b, c);
This decouples A
from the details of instantiating B
s and C
s, by injecting it with those dependencies (thus, dependency injection).
To decouple A
from the implementation, you'll want to create interfaces for the functionality of B
and C
that A
cares about. Say, Bable
and Cable
. Then A
can accept as its constructor parameters a Bable
and a Cable
, and doesn't care what class happens to implement those interfaces, or how the implementation works---just that it conforms to the contracts laid out by Bable
and Cable
.
Here is a fully fleshed-out example of what I am talking about: https://gist.github.com/2402514
Upvotes: 1
Reputation: 28812
You can specify the concrete objects A should use in its constructor then store them as member variables. This way you do not have to create the objects more than once, and can supply objects of other classes (that implement the same interface as B, say)
public class A
{
private BIface b;
private CIface c;
public A(BIface b, CIface c) {
this.b = b;
this.c = c;
}
}
interface BIface {
// required B methods
}
public class B implments BIface
{
// implement the interface
}
similarly for C/CIface
Use it like this:
BIface c = new C(); // or some other class also implementing CIface
BIface b = new B(c); // or some other class also implementing BIface
A a = new A(b, c);
Upvotes: 0