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

后端 未结 2 903
青春惊慌失措
青春惊慌失措 2020-12-10 16:33

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

I found an exp

2条回答
  •  生来不讨喜
    2020-12-10 17:19

    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  the type of stream elements
     * @return a singleton sequential stream
     */
    public static Stream of(T t) {
        return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
    }
    
    /**
     * Returns a sequential ordered stream whose elements are the specified values.
     *
     * @param  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 Stream 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

提交回复
热议问题