Avoiding RTTI In Java
If I have a superclass, say Animal,
and two subclasses: Zebra and Giraffe,
If I decide to define a Vector of Animals:
Vector <Animal> animals = new Vector();
an开发者_运维技巧d I want to say: You can add Giraffes, but you must own at least one Zebra first.
What is the best way to do this without using RTTI? (instanceof)
Define your own class:
class Animals extends Vector<Animal>
{
public Animals(Zebra z) { add(z); }
}
Two additional points:
- It is recommended to prefer the use of ArrayList over Vector.
- You may want to override the remove() method to make sure a Zebra always stays in the collection.
Personally, I would go for a design that does not use inheritance at all. So instead of subclassing vector (or ArrayList) my class will delegate to them:
class Animals extends
{
private final Vector<Animal> inner = new Vector<Animal>();
public Animals(Zebra z) { add(z); }
// Delegate to whatever methods of Vector that Animals need to support, e.g.,
void add(Animal a) { inner.add(a); }
...
}
精彩评论