I am trying to create a tree structure (a binary tree) that is capable of holding two different types of class (a sphere and a rectangle).
For obvious reasons my sphere and rectangle will have different methods for getting their size (getSize()) and I also intend to have a constructor (for both classes) thats takes two objects (two spheres OR two rectangles) and combines them to create a larger sphere or rectangle.
How should I approach coding a node so that it can store either a sphere or a rectangle at a node calling the appropriate methods when required?
Would a simple interface accomplish this if i cast objects to the type i need?
Thanks,
DMcB
Would a simple interface accomplish this if i cast objects to the type i need?
An interface Shape would seem appropriate. If done right, you won't need a cast at all when inserting an item.
I would create three classes. An abstract class Shape that contains all common code for rectangles and spheres.
public abstract class Shape{
// contains all common code related to shapes
// such as child elements
Shape parentNode; // This will help navigate up
List<Shape> children; // This will help navigate down the tree
// Define, merge, split methods which are common to all shapes
// define shape specific methods
}
public class Rectangle : Shape{
// Implement shape's abstract methods for this class
}
public class Sphere : Shape{
// Implement shape's abstract methods for this class
}
All shape specific methods should be left abstract such as getSize(), drawShape(), mergeShape().
Also, maybe not relevant but the Composite design pattern might be of good use for this problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With