Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

java - Why LocalDate, LocalTime and Stream objects use a factory method of() instead of a constructor?

Why LocalDate, LocalTime, Stream, etc. objects use a factory method of() instead of a constructor?

I found an explanation of why a factory methods should be used instead of new here. This answer gives a number of reasons, but the only thing that is relevant to Java Date/Time API is the following:

unlike constructors, they are not required to create a new object each time they’re invoked

As LocalDate and LocalTime are immutable, it probably makes sense to use a factory and reuse existing objects instead of creating a new object every time.

Is it the reason why objects like LocalDate and LocalTime are created with a factory method (i.e., LocalDate.of())? Are there any other reasons?

Also, Stream objects are mutable. Why a factory method (Stream.of()) is used to create a Stream?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why a factory method (Stream.of()) is used to create a Stream?

Using a factory method means you don't need to know the exact class used. This is a good example as Stream is an interface and you can't create an instance of an interface.

From the source for Stream.of

/**
 * Returns a sequential {@code Stream} containing a single element.
 *
 * @param t the single element
 * @param <T> the type of stream elements
 * @return a singleton sequential stream
 */
public static<T> Stream<T> of(T t) {
    return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}

/**
 * Returns a sequential ordered stream whose elements are the specified values.
 *
 * @param <T> the type of stream elements
 * @param values the elements of the new stream
 * @return the new stream
 */
@SafeVarargs
@SuppressWarnings("varargs") // Creating a stream from an array is safe
public static<T> Stream<T> of(T... values) {
    return Arrays.stream(values);
}

Note: these methods call other factory methods.

You can see you get different constructions depending on how it is called. You don't need to know this or that the ultimate class created which is a ReferencePipeline.Head


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...