6

In core Java 8's date and time library, i.e. those classes in the package java.time, I found a special common trait: there is no public constructor in each class of this package, and thus all classes can be instantiated only through some static methods such as of, now etc. In this sense, the classes inside java.time resembles the factory design pattern. However, these classes do differ from factory design pattern in that the essence of factory design pattern is to loose couple the code to instantiate various types of objects with a common method (usually static), and thus the type of the returned object instance is determined until runtime.

However, esp. in the class java.time.LocalDate and java.time.ZonedDateTime, the keyword factory was mentioned. One can find the keyword factory from:

So I would like to know did java.time.LocalDate and java.time.ZonedDateTime apply the factory design pattern at all? If not, what design pattern did they apply?

Rui
  • 3,454
  • 6
  • 37
  • 70

2 Answers2

2

I see at least three reasons for this choice (and yes that is the factory pattern) :

This way it could in future return a specialized LocalDate for example, which could be extended only internally (since there are no user-availabe constructors). This way the specialized classes would not be exposed to the clients - only known internally. That seems like exactly your point about different types at runtime - at the moment they don't return any particular subtype, but they might in future.

It would potentially cache some instances for example - I don't think it does that at the moment, but that still remains an option.

Some of the methods have descriptive names: ofYearDay, ofInstance, etc.

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • thanks a lot for your opinion :) there is one point I feel doubt: the `LocalDate` is `final` class and *immutable*, so there seems not to be any *extension* in the future – Rui Aug 09 '17 at 09:24
2

I think that they wanted to apply the rule

Consider static factory methods instead of constructors

from the book Effective Java by Joshua Bloch.

The goal of that rule is that static methods can be more descriptive as constructors, because a method has a name.

For example:

ZonedDateTime.now();

is more descriptive than

new ZonedDateTime();

is, isn't it?

You might also want to read: Joshua Bloch #Item 1: Consider static factory methods instead of constructors

René Link
  • 48,224
  • 13
  • 108
  • 140
  • Thanks a lot :) This is what I would like to know. So it is *static factory method*. As the book - Effective Java - you mentioned told: a static factory method is not the same as the Factory Method pattern from Design Patterns [Gamma95, p. 107]. The static factory method described in this item has no direct equivalent in Design Patterns – Rui Aug 09 '17 at 12:17