静态方法或单件,该选哪一个? [英] Static methods or Singleton, which one to choose?
问题描述
可能重复:
<一href="http://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern">Difference静态类和单例模式之间?
这是更好的在Java中,
Which is better in Java,
实施公共静态方法,像
Factory.createLoginRequest()
或实施Singleton模式,比如
or implementing Singleton pattern, like
Factory.getInstance().createLoginRequest()
(Boths会返回一个Request对象。)
(Boths will return a Request object.)
哪一个是更好的为什么的?
推荐答案
从维基百科:
请注意一类和单的一个简单的静态实例之间的区别:虽然一个单可以被实现为一个静态实例,它也可以被懒惰地构造,直到需要无需存储器或资源。另一个显着区别是,静态成员类无法实现接口,除非该接口是一个简单的标记。因此,如果类必须实现由接口pssed一个守合同$ P $,它真的是一个单例。
Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, it really has to be a singleton.
这篇关于静态方法或单件,该选哪一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!