考虑提供静态工厂方法而不是构造函数 [英] Consider providing static factory methods insteads of constructors
问题描述
允许客户端获取实例的类的常规方法是提供公共构造函数。另一种方法是提供一个公共静态工厂方法,它只是一个返回类实例的静态方法。什么是使用静态工厂方法的利弊?
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, which is simply a static method that returns an instance of the class. What are pros and cons by using static factory method?
推荐答案
有效Java一书的这一章解释得很好:考虑静态工厂而不是构造函数。它以你能理解的最佳方式解释了它们的所有优点和缺点。
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:
优势:
- 静态工厂方法的一个优点是,与构造函数不同,它们具有名称。
- 静态工厂方法的第二个优点是,与构造函数不同,它们不需要在每次调用时都创建新对象。
- 静态工厂方法的第三个优点是,与构造函数不同,它们可以返回其返回类型的任何子类型的对象。
- 静态工厂方法的第四个优点是它们减少了创建参数化类型实例的详细程度(在Java 7中可以忽略这一点)
- 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)
缺点:
-
主要缺点
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.
这篇关于考虑提供静态工厂方法而不是构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!