java - 现有抽象类 Clock 上的新接口(interface) java.time.InstantSource 的主要目的是什么?

标签 java java-time java.time.instant

全新界面 java.time.InstantSource在 Java 17 中添加。如果该接口(interface)的所有实现都是 Clock,那么该附加抽象的用例是什么?实现呢?

最佳答案

感谢 NoDataFound 提供评论中的链接(链接在此答案底部重复)。 Stephen Colebourne(java.time 的原始开发人员)的“错误”报告说:

Problem

Since java.time was first added in Java 8, it has become apparent that there is a missing concept - a source of Instant independent of time zone. Put simply, if the only thing you want is an Instant, then Clock isn't the right API because it forces you to think about time zones.

A good architectural design for time-based code would have a separation between the abstraction of the OS clock (dependency injected for unit testing), and the time zone linked to user localization. Passing these two things around separately is key. To achieve this as it stands, developers must either write their own TimeSource or InstantSource interface, or use Clock and "hold their nose" to ignore the time zone held within.

A Supplier<Instant> obviously performs similar functionality, but it lacks discoverability and understandability. Plus, injecting generified interfaces tends to be painful.


用我的话来说:Clock class 被引入作为当前时间的来源。从概念上讲,当前时间的来源应该独立于时区。 Clock不过有一个时区。可能出于实际目的,以便您可以从中绘制各种日期时间对象:LocalDate , ZonedDateTime , LocalTime , 等等。InstantSource询问的接口(interface)实现了我刚刚描述的时钟概念:独立于时区的当前时间的来源。当带时区的时钟对于您的目的来说太重了。
两者的目的之一ClockInstantSource可测试性:通过这些,您可以控制运行测试时将哪个时间视为“当前时间”,这在您想要可重复的测试时通常是必需的。

… if anyway all implementations of that interface are Clock implementations also?


我还没有检查是否全部InstantSource Java 17 附带的实现是 Clock子类。即使是这种情况,(1) 也不是重点,(2) 没有人阻止您实现 InstantSource那不是 Clock .抽象是编程中的一个关键概念。如果您只想要 Instant s,那么你想针对一个只能给你的简单界面进行编程Instant s。 InstantSource抽象出这样一个事实,即您正在使用的对象也可以扮演 Clock 的角色。在其他一些情况下。 InstantSource interface 是应用备受推崇的 Façade 设计模式的学校示例(链接如下)。借助来自错误系统的 Stephen Colebourne 的描述性词语,该界面使程序员在获得 Instant 时不再“捂着 Nose ”。 s。
链接
  • Add java.time.InstantSource在 OpenJDK 错误系统中。
  • Facade pattern在维基百科上。
  • 关于java - 现有抽象类 Clock 上的新接口(interface) java.time.InstantSource 的主要目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69199722/

    相关文章:

    java - Kotlin Android/Java 字符串日期时间格式,API21

    postgresql - Instant 与 ZonedDateTime

    java.time.OffsetDateTime : Unable to obtain OffsetDateTime from TemporalAccessor

    java - 小程序中的双缓冲如何工作?

    java - "could not find or load main class"调度java程序时

    java - 如何避免时差为负时间?

    java - JsonFormat.Shape.NUMBER_INT 为 LocalDate 序列化了什么?

    java - 基于相关权重在 Java 中规范化随机数

    java - 如何使用 Spring-data-elastic 查询 Elastic

    java - 解析时出错 2018-05-01T00 :00:00 date using Instant. 解析