Static methods or Singleton, which one to choose?

2019-03-12 14:07发布

Possible Duplicate:
Difference between static class and singleton pattern?

Which is better in Java,

implementing public static methods, like

Factory.createLoginRequest()

or implementing Singleton pattern, like

Factory.getInstance().createLoginRequest()

(Boths will return a Request object.)

Which one is better and why ?

4条回答
Anthone
2楼-- · 2019-03-12 14:33

It depends.

Choose singletons, because:

  • In general, I'd say a singleton is slightly neater because it allows you to do some initialization of the singleton object in/from the (private) constructor.
  • When it is later decided this object should no longer be a singleton (due to new insights or new requirements), it is easier to refactor it: you just need to change all the places that get the instance, instead of all calls to the static methods.

Use static methods, because:

  • In the specific case of android, you might prefer static methods for performance - I suspect calling a static function might be a bit faster (easier to optimize for the compiler) compared to calling a method on a singleton object.
查看更多
一纸荒年 Trace。
3楼-- · 2019-03-12 14:33

It depends. Singleton concept considers a limitation on object initialization. In other words, singleton object must be the only instance of a singleton class in the runtime. But if you just need to create objects of some family of classes, then go with factory method pattern.

查看更多
放荡不羁爱自由
4楼-- · 2019-03-12 14:35

from wikipedia:

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.

查看更多
狗以群分
5楼-- · 2019-03-12 14:41

I'd go for the Singleton because it allows you to use Java's object-oriented features like inheritance (method overriding) which won't work for static methods.

查看更多
登录 后发表回答