Spero che questo risponda solo alla domanda principale qui.
Ci sono già poche ottime risposte in SO . Li citerò solo.
Risposta migliore, per Heinzi :
A singleton is used to introduce some kind of global state to an
application. If it is stateless, I also don't see the point of using a
singleton, unless
- you expect to extend it with state in the foreseeable future or
- you need an object instance for some particular technical reason (for example, for the C#
SyncLock
statement, although this is
already quite far-fetched) or
- you need inheritance, i.e., you want to be able to easily replace your singleton with another one using the same interface but a
different implementation. For example, the
Toolkit.getDefaultToolkit()
method in Java will return a singleton
whose exact type is system dependent.
Alto commento pertinente, per back2dos :
(...) singletons are misused to introduce global states. The purpose of a singleton is not to make an object globally available, but to enforce that an object is instantiated only once. Global objects are a necessary evil. Unless really required, one should try not to use them, since they generally lead to high coupling, with SomeSingleton.getInstance().someMethod() all over the place.
tzaman ha anche scritto una buona risposta:
I could see a case for a stateless singleton being used instead of a
static methods class, namely for Dependency Injection.
If you have a helper class of utility functions that you're using
directly, it creates a hidden dependency; you have no control over who
can use it, or where. Injecting that same helper class via a stateless
singleton instance lets you control where and how it's being used, and
replace it / mock it / etc. when you need to.
Making it a singleton instance simply ensures that you're not
allocating any more objects of the type than necessary (since you only
ever need one).
E infine Sebastien si è anche risposto abbastanza bene:
Actually i've found another answer not mentionned here: static methods are harder to test.
It seems most test frameworks work great for mocking instance methods but many of them no not handle in a decent way the mock of static methods.
Detto questo, ti consiglio di utilizzare il modello Toolbox .