c++公历和儒略历的继承
我遇到了这样的困境,我需要在格里高利历和儒略历的不同继承类型之间进行选择。我想要一个名为 Date 的类作为基类。 我的问题如下:我是否应该有一个继承自日期类的格里高利历类和具有相同功能的儒略历类?或者应该只有 Gregorian 类继承自 Date 类,而 Julian 类继承自 Gregorian 类,反之亦然?或者我应该在 Date 下有一个继承自 Date 的类,并让 Gregorian 和 Julian 继承自该类?
Date Date Date Date
Gregorian Julian Gregorian Julian New class
Julian Gregorian Gregorian Julian
我个人会选择第一个选择,两者都继承自 Date,这是一个不错的选择。我可以得到一些对此的意见吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不知道日历系统的内部细节,但我确信很难不低估它们微妙的复杂性。仅此一点就让我绝对不想想要在类层次结构中混合实现。
我会使用
共享实用程序,以避免不必要的代码重复PS。在经典的“Liskov”意义上,您可以有一个抽象基类 Date,它只是“命名”所有(大多数?)日历系统通用的概念。然而,我真的很怀疑附加值会是多少。我可以看到它会导致很多混乱(它会邀请代码在任何或所有代码中混合日期的子类型,并且使用日期时间类的所有代码必须准备好始终处理整个范围)。
顺便说一句,请查看Noda Time 和乔达时间。人们普遍认为这些备受推崇的图书馆设计得特别好。
I don't know the inner details of the calendar systems, but I'm sure it is hard not to underestimate their subtle complexities. That alone would make me absolutely not want to mix the implementation in a class hierarchy.
I'd go with
PS. In the classical 'Liskov' sense, you could have an abstract base class Date that just 'names' concepts common to all (most?) calendar systems. However, I'm really doubting what the added value would be. I could see it lead to a lot of confusion (it invites code to mix subtypes of Date in any or all code and all code using your datetime classes must be prepared to handle the whole gamut always).
By the way, have a look at Noda Time and Joda Time. These well-respected libraries are generally thought to be especially well-designed.
公历和儒略历是日历的两种类型。对它们来说,从共同的基类继承比相互继承更好。
一个例子可以在乔达时间中找到,它具有公历和儒略年表作为公共基本年表的不同子类。
在标准 Java 库中可以找到一个反例,其中同一个类支持公历和儒略历。
Gregorian and Julian calendars are two types of calendar. It would be better for them to inherit from a common base class than inherit from each other.
An example can be found in Joda time, which has Gregorian and Julian chronologies as different subclases from a common base chronology.
A counter-example can be found in the standard Java library, in which the Gregorian and Julian calendars are supported by the same class.
Calendar
不是Date
,因此两者都不需要从Date
继承。Calendar
最多应该对Dates
进行操作。或者,Date
可能可以将其自身从一种类型转换为另一种类型。您究竟想做什么?为什么还没有在第三方库中完成?
A
Calendar
is not aDate
so there is no need for either to inherit fromDate
.At most, a
Calendar
should operate onDates
. Or perhaps aDate
could convert itself from one kind to another.What exactly are you trying to do and why isn't it already done in a 3rd party library already?