Consider providing static factory methods insteads of constructors

后端 未结 5 1306
清酒与你
清酒与你 2020-12-06 08:38

The normal way for a class to allow a client to obtain an instance is to provide a public contructor. Another way to do that is providing a public static factory method, whi

5条回答
  •  半阙折子戏
    2020-12-06 09:20

    This chapter from the book Effective Java explains it well: Consider Static Factory instead of Constructors. It explains all the pros and cons for both of them in the best way you can understand.

    Just to quote the advantages and disadvantages from the book:

    Advantages:

    • One advantage of static factory methods is that, unlike constructors, they have names.
    • A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.
    • A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.
    • A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances (This one can be ignored in Java 7)

    Disadvantages:

    • The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed

    • A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.

    You can study them in more detail in the link I gave.

提交回复
热议问题