gpt4 book ai didi

java - 与 child 分享基本类型列表

转载 作者:搜寻专家 更新时间:2023-10-31 08:15:23 25 4
gpt4 key购买 nike

我有一个基类 ShapeManager带有我想要的形状列表 enumerate() .然后就是专精ColoredShapeManager哪个想要加工专业ColoredShape s 而不是 Shape小号:

+----------------+      +-------------------------------------+
| Shape | | ShapeManager |
|----------------| |-------------------------------------|
| + id: int | | # shapes: List<Shape> |
| | | |
| | | + ShapeManager() { |
| | | shapes.add(new Shape()); |
| | | } |
| | | |
| | | + abstract void enumerate() { |
| | | for (Shape s: shapes) { |
| | | // use s |
| | | } |
| | | } |
+----------------+ +-------------------------------------+
^ ^
| |
+ +
+----------------+ +-------------------------------------+
| ColoredShape | | ColoredShapeManager |
|----------------| |-------------------------------------|
| + color: int | | + ColoredShapeManager() { |
| | | shapes.add(new ColoredShape()); |
| | | } |
| | | |
| | | + abstract void enumerate() { |
| | | for (Shape s: shapes) { |
| | | // use (ColoredShaped) s |
| | | // will fail for Shapes |
| | | } |
| | | } |
+----------------+ +-------------------------------------+

我不确定 ShapeManager 是否应该共享 shapes: List<Shape>与其 child 这似乎有缺陷,因为ColoredShapeManager.enumerate()想要过程 ColoredShape秒。因此它会转换元素,但有些元素(由基类添加的)类型为 Shape并且转换会失败。

即:

  • 两种类型的形状最终都在列表中 shapes .
  • enumerate()在子管理器中应该可以访问 ColoredShape .

我是否应该拆分列表并在两个管理器中分别创建私有(private)列表?然后在 child 中枚举只会迭代“它的”形状类型并调用 parent 的 enumerate()在开始/结束。

最佳答案

您可以将形状类型添加为管理器类的“类型参数”。所以基本上,ColoredShapeManager可以扩展ShapeManager<ColoredShape>还有这个T将是您内部的类型 List数据结构。另外,如果您的 ColoredShapeManager不对 ColoredShapes 执行任何特定操作,我认为它甚至不需要新类(class)。但话又说回来,这取决于您构建应用程序/设计的方式。

关于java - 与 child 分享基本类型列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14242444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com