Static methods or Singleton, which one to choose? [closed]
Possible Duplicate:
Difference between static cla开发者_如何转开发ss 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 ?
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.
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.
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.
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.
精彩评论