我会创建三个类.
一个抽象类Shape,包含矩形和球体的所有常用代码.
public abstract class Shape{
// contains all common code related to shapes
// such as child elements
Shape parentNode; // This will help navigate up
List 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
}
所有形状特定的方法都应该是抽象的,例如getSize(),drawShape(),mergeShape().
此外,也许不相关,但the Composite design pattern可能会很好地解决这个问题