属性的两种可能类型

发布于 2024-10-11 21:33:54 字数 285 浏览 6 评论 0原文

我有一个类,它是复合模式中的叶子。该类有一个属性,可以是 A 类型,也可以是 B 类型。它们唯一的公共接口是 Object 类型。

我该如何支持这个。

我可以

  1. 为每种类型提供一个添加方法。然而,这意味着我应该有类型 A 和 B 的两个属性,并且当我想要获取正确的属性时应该检查 null。

  2. 有一个对象类型的属性。这意味着当我获取该属性时,我必须检查它是哪种实例。

此类问题的最佳解决方案是什么?或者有更好的解决方案吗?

I have a class that is a leaf in the composite pattern. This class has a property that can be either of type A or type B. Their only common interface is of type Object.

How should I support this.

I can

  1. have a add method for each type. That would however mean that I should have two properties of type A and B and should check for null when I want to get the right property.

  2. have one property of type of Object. That would mean I had to check to see which kind of instance it is when I get the property.

What is the best solution for this type of problem? Or any better solutions?

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

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

发布评论

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

评论(2

多彩岁月 2024-10-18 21:33:54

就我个人而言,我会选择单个 Object 属性方法。记录属性可能返回的对象类型,并让调用代码使用可用的语言功能来确定对象类型,并根据需要进行强制转换。实现两个属性有点重新发明语言的“is-a”运算符,并且如果您需要添加更多可能的类型,很快就会变得难以管理。

Personally I would choose the single Object property approach. Document what types of objects the property may return, and let the calling code use the available language features to determine the object type, and cast as necessary. Implementing two properties is kinda reinventing the "is-a" operator of your language, and will quickly become unmanageable if you ever need to add more possible types.

情愿 2024-10-18 21:33:54

如果您使用支持类型抽象的语言(例如 Java 中的泛型或 C++ 中的模板),您可以将该属性设置为泛型类型。如果没有,请使用对象,为每种类型提供一个方法只是一个丑陋的黑客(并且无法维护,如果您稍后添加更多类型)。

Well if you are using a language that supports type abstraction (like Generics in Java or Templates in C++) you can just set that property as a generic type. If not, use Object, Having a method for each type is just an ugly hack (and unmaintanable, if you add more types later).

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