在 Java 中避免 RTTI

发布于 2024-08-26 20:01:26 字数 302 浏览 5 评论 0原文

如果我有一个超类,例如动物

和两个子类:斑马长颈鹿

如果我决定定义一个动物向量:

Vector <Animal> animals = new Vector();

并且我想说:你可以添加长颈鹿,但你必须先拥有至少一只斑马

不使用 RTTI 的最佳方法是什么? (实例

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();

and 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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

国粹 2024-09-02 20:01:27

定义您自己的类:

class Animals extends Vector<Animal>
{
   public Animals(Zebra z) { add(z); }
}

另外两点:

  • 建议优先使用 ArrayList 而不是 Vector。
  • 您可能需要重写remove()方法以确保Zebra始终保留在集合中。

就我个人而言,我会选择完全不使用继承的设计。因此,我的类将委托给它们,而不是子类化向量(或ArrayList):

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); }

   ...
}

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); }

   ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文