ans*_*nie 3 java design-patterns naming-conventions
从命名约定和可用性来看:类中“from”与“of”方法有什么区别?何时创建每一个?
请参阅作为Oracle 提供的java.time教程的一部分发布的指南方法命名约定。
\n去引用:
\n\n\n\n
of创建一个实例,其中工厂主要验证输入参数,而不是转换它们。
\n
\xe2\x80\xa6 和 \xe2\x80\xa6
\n\n\n\n
from将输入参数转换为目标类的实例,这可能会丢失输入中的信息。
\n
有关实际示例,请参阅java.time类,例如LocalDate、LocalTime、Instant、OffsetDateTime、ZonedDateTime、LocalDateTime等。
LocalDate x = LocalDate.of( 2021 , Month.MARCH , 27 ) ; // Directly injecting the three parts of a date (year, month, day) without any need to parse or process the inputs other than basic data validation such as day within appropriate range of 1-28/31 for that year-month.\n\nZoneId zoneId = ZoneId.of( "Africa/Casablanca" ) ; // This string is the official name of this time zone. Can be mapped directly from name to object, with no real processing, parsing, or conversions involved.\nZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;\nLocalDate y = LocalDate.from( zdt ) ; // Converting between types. Data loss involved, losing (a) time-of-day and (b) time zone.\nLocalDate z = zdt.toLocalDate() ;\nRun Code Online (Sandbox Code Playgroud)\n\nx.toString(): 2021-03-27\ny.toString(): 2021-05-25\nz.toString(): 2021-05-25\nRun Code Online (Sandbox Code Playgroud)\n