问题描述
是否有需要类的伴生对象(单例)的情况?为什么我要创建一个类,比如 Foo
并为它创建一个伴生对象?
Is there a case where a companion object (singleton) for a class is needed? Why would I want to create a class, say Foo
and also create a companion object for it?
推荐答案
伴随对象基本上提供了一个可以放置类静态"方法的地方.此外,伴生对象或伴生模块可以完全访问类成员,包括私有成员.
The companion object basically provides a place where one can put "static-like" methods. Furthermore, a companion object, or companion module, has full access to the class members, including private ones.
伴随对象非常适合封装工厂方法之类的东西.例如,不必到处都有 Foo
和 FooFactory
,您可以让一个带有伴随对象的类承担工厂职责.
Companion objects are great for encapsulating things like factory methods. Instead of having to have, for example, Foo
and FooFactory
everywhere, you can have a class with a companion object take on the factory responsibilities.
这篇关于在 Scala 中拥有伴生对象的基本原理是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!