我最近正在浏览一个 Netflix open source project
在那里我发现了 final 类和私有(private)构造函数的使用。我完全知道
- final是为了避免继承
- private 是不允许实例化
但我只是想知道为什么将它们一起使用。虽然方法是静态的,所以我们可以在不实例化的情况下使用它们,但仍然渴望了解其背后的设计原则。
最佳答案
有了这段代码,你将拥有这些功能
- 不允许任何人子类化(
扩展
)您的类 - 不允许实例化你的类
- 将变量或类设置为 final 可以提高性能(虽然不多,但在大型项目中作为常见做法使用会有所不同)
在这种情况下,我看不到用于获取实例的单例模式,因此,恕我直言,您正在寻找 Netflix API 中的帮助程序/实用程序类,开发团队在其中使用了一些标准实践来确保用户 < em>以正确的方式使用他们的类:
StaticFinalClassExample.methodYouWantToCall();
此外,查看您链接的类(class):
/**
* This class consists exclusively of static methods that help verify the compliance of OP1A-conformant....
*/
和:
//to prevent instantiation
private IMFConstraints()
{}
添加:
如果您想了解更多信息,请查看 Joshua Bloch's Effective Java (2nd Edition) 中的第 4 项
:
Item 4: Enforce noninstantiability with a private constructor
Occasionally you’ll want to write a class that is just a grouping of static methods and static fields. Such classes have acquired a bad reputation because some people abuse them to avoid thinking in terms of objects, but they do have valid uses.
- They can be used to group related methods on primitive values or arrays, in the manner of
java.lang.Math
orjava.util.Arrays
.- They can also be used to group static methods, including factory methods (Item 1), for objects that implement a particular interface, in the manner of
java.util.Collections
.- Lastly, they can be used to group methods on a
final
class, instead of extending the class.Such utility classes were not designed to be instantiated: an instance would be nonsensical. In the absence of explicit constructors, however, the compiler provides a public, parameterless default constructor. To a user, this constructor is indistinguishable from any other. It is not uncommon to see unintentionally instantiable classes in published APIs.
Attempting to enforce noninstantiability by making a class abstract does not work. The class can be subclassed and the subclass instantiated. Furthermore, it misleads the user into thinking the class was designed for inheritance (Item 17).
There is, however, a simple idiom to ensure noninstantiability. A default constructor is generated only if a class contains no explicit constructors, so a class can be made noninstantiable by including a private constructor.
关于java - 带有私有(private)构造函数的最终类,设计原则是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39078908/