I have a set of interfaces. I have two implementations of these interfaces. These interfaces have methods which accept other interfaces from the set.
The implementation implements the interfaces. The problem occurs on the methods which accept interfaces from the set. like
The implementation is something like this
As you can see the problem is I need to cast from the interface type to the concrete type all over the place. This is complicating my design, and it dont feel very save. Is there a pattern that can allow me to avoid this casting?
Yes but having an ID is part of the way the implementation is formed. Other implementations like file based ones, do not need/use IDs. But adding the ID is the one solution I have entertained and just ignore it in the file style implementation.
Joined: Jan 29, 2003
If the objects in your collection do not all share some common type (base class or interface) you'll have to check to see what you have:
Life is surely easier if they all have the common type. In JDK 5 you can use generics to enforce the common type at put time and avoid casting at get time. But putting an interface on something that doesn't need it is always troubling, too.
Why are you storing only the ID of the concrete Child in the Parent instead of storing the IChild itself? How exactly is the ID used, other than for storing in the Parent?
One method would be to create a surrogate ID for those children that don't have one. For the file-based ones, simply create an IdGenerator class that gives out a sequential ID from an internal counter. This assumes that the IDs don't need to be kept between program runs, though.
This would allow you to add getID() to the Child interface and remove all the downcasting.