Hiding a constructor behind a static creator method?

前端 未结 9 1599
我在风中等你
我在风中等你 2021-01-04 00:47

I\'ve recently discovered an interesting way to create a new instance of an object in Google Guava and Project Lombok: Hide a constructor behind a static creator method. Thi

9条回答
  •  执念已碎
    2021-01-04 01:19

    There are a number of reasons why you might prefer a static factory method instead of a public constructor. You can read Item 1 in Effective Java, Second Edition for a longer discussion.

    1. It allows the type of the object returned by the method to be different than the type of the class that contains the method. In fact, the type returned can depend on the parameters. For example, EnumSet.of(E) will return a different type if the emum type has very few elements vs if the enum type has many elements (Edit: in this particular case, improving performance for the common case where the enum doesn't have many elements)
    2. It allows caching. For instance, Integer.valueOf(x) will, by default, return the same object instance if called multiple times with the same value x, if x is between -128 and 127.
    3. It allows you to have named constructors (which can be useful if your class needs many constructors). See, for example, the methods in java.util.concurrent.Executors.
    4. It allows you to create an API that is conceptually simple but actually very powerful. For instance, the static methods in Collections hides many types. Instead of having a Collections class with many static methods, they could have created many public classes, but that would have been harder for someone new to the language to understand or remember.
    5. For generic types, it can limit how much typing you need to do. For example, instead of typing List strings = new ArrayList() in Guava you can do List strings = Lists.newArrayList() (the newArrayList method is a generic method, and the type of the generic type is inferred).

    For HashBiMap, the last reason is the most likely.

提交回复
热议问题