假设我有一个简单的继承结构,如下所示:
class Shape {
int id;
}
class Circle extends Shape {
int radius;
}
class Square extends Shape {
int length;
}
class ToyBox {
List<Shape> shapes;
}
这些对象不能以任何方式扩充(不能添加方法/字段/访问器。以任何方式更改文件),并且应被视为不可变/最终的。我必须将每个形状对象返回到我正在使用的系统的另一部分,并在每个项目旁边添加一些额外的信息。例如:
class extended Shape {
int id;
}
class ExtendedCircle extends ExtendedShape {
public Circle circle;
public Blah circleStuff;
public ExtendedCircle(Circle circle) {...}
}
class ExtendedSquare extends ExtendedShape {
public Square square;
public Blah squareStuff;
public ExtendedSquare(Square square) {...}
}
给定形状玩具盒,我能想到完成此任务的唯一方法是迭代形状列表,执行检查实例并强制转换为圆形、方形等,然后构造每个相应的“扩展” ” 对象。这让我有点不舒服,所以我想知道是否有另一种方法来设计这样的系统?
最佳答案
如果您需要避免转换和使用 instanceof
运算符,您可能需要考虑使用 Vistor设计模式。将其应用到您的示例中可能如下所示:
class Shape {
int id;
public void visitingShape(ToyBox box) {
box.visitingShape(this);
}
}
class Circle extends Shape {
int radius;
public void visitingShape(ToyBox box) {
box.visitingCircle(this);
}
}
class Square extends Shape {
int length;
public void visitingShape(ToyBox box) {
box.visitingSquare(this);
}
}
class ToyBox {
List<Shape> shapes;
public visitingShape(Shape shape) {
// Do logic related to the shape
}
public visitingCircle(Circle shape) {
// Do logic related to the circle
}
public visitingSquare(Square shape) {
// Do logic related to the square
}
}
关于java - 避免在 java 继承中进行强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46507286/