为什么LocalDate,LocalTime和Stream对象使用()的工厂方法而不是构造函数? [英] Why LocalDate, LocalTime and Stream objects use a factory method of() instead of a constructor?

查看:593
本文介绍了为什么LocalDate,LocalTime和Stream对象使用()的工厂方法而不是构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 LocalDate LocalTime Stream 等。对象使用工厂方法 of()而不是构造函数?

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

我找到了工厂原因的解释应使用方法代替 new 此处。这个答案有很多原因,但与Java Date / Time API相关的唯一原因如下:

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 LocalTime 是不可变的,使用工厂并重用现有对象而不是每次都创建新对象可能是有意义的。

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.

这就是为什么创建像 LocalDate LocalTime 这样的对象的原因工厂方法(即 LocalDate.of())?还有其他原因吗?

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?

此外, Stream 对象是可变的。为什么工厂方法( Stream.of())用于创建

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

推荐答案


为什么使用工厂方法(Stream.of())来创建流?

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

使用工厂方法意味着您不需要知道所使用的确切类。这是一个很好的例子,因为 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.

来自 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.

根据调用方式的不同,您可以看到不同的结构。您不需要知道这个或者最终创建的类是 ReferencePipeline.Head

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

这篇关于为什么LocalDate,LocalTime和Stream对象使用()的工厂方法而不是构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆