比较器作为静态字段 - 接口还是实现?

发布于 2024-09-19 18:24:04 字数 346 浏览 1 评论 0原文

我有一个已经具有“自然”顺序的类,并且希望定义一个不同的比较器,可以类似于 String.CASE_INSENSITIVE_ORDER 来使用 - 即,将其定义为要引用的实例化静态字段当需要时。

对于实际比较类型的接口 Foo(它将是 Comparator),我赞成将其放在那里而不是 FooImpl (在这种特定情况下只有一个实现,如果有所作为)。它是使用类似于 String 的内部类来实现的,当然该类必须是公共的,因为 Foo 是一个接口。

想知道将它放在 FooImpl 而不是 Foo 中是否更好,如果是的话为什么?另外,我不关心实现类的公共可见性,但它应该是一个独立的单独包可见实体吗?

I have a class that already has a 'natural' order, and wish to define a different Comparator that can be used similar to String.CASE_INSENSITIVE_ORDER - i.e., define it as an instantiated static field to be referred to when needed.

With an interface Foo which is the actual comparison type (it will be Comparator<Foo>), I'm in favor of putting it there rather than FooImpl (only one implementation in this specific case, if that makes a difference). It is implemented using an inner class similar to the String one, except of course that class must be public since Foo is an interface.

Wondering if it is better to put it in FooImpl instead of Foo, and if so why? Also I don't care about the public visibility of the implementing class, but should it be a standalone seperate package visible entity instead?

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

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

发布评论

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

评论(2

眼泪都笑了 2024-09-26 18:24:04

如果是特定于接口的,则放入接口。如果具体到实施,就付诸实施。这也是最有道理的。当前的实施数量并不重要。无论如何,您始终可以为实现提供其自己的特定于实现的比较器。

If it's specific to the interface, put in interface. If it's specific to the implementation, put in implementation. That makes also the most sense. The current amount of implementations don't matter. You can anyway always provide an implementation its own implementation-specific comparator.

清浅ˋ旧时光 2024-09-26 18:24:04

Comparator 是否打算在 FooImpl 之外使用?如果是这样,您可以像将枚举一样将其放入界面中。如果使用新比较器的任何代码仅使用 Foo 接口,我不会将其放入 FooImpl 中。

他们不需要仅仅为了使用比较器而了解 FooImpl。

Is the Comparator intended to be used outside of FooImpl? If so, you can just put it in the interface as you would an enum. I'd not put it in FooImpl if any of the code using the new comparator are using the Foo interface only.

They shouldn't need to know about FooImpl just to use the Comparator.

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