As Arne said, if the class contains only methods then making it a
singleton may not make sense.
Making a class a Singleton (or something close to one) really does only
one thing for you: allows your class to exhibit polymorphic behaviour,
which a static class cannot do.
This means that you can have your class implement interfaces, have it
participate in the inheritance hierarchy by having child classes
(although then it's not technically a singleton any more, but this can
be useful nonetheless), etc. These things mean that you can pass your
class to methods that accept classes that implement those interfaces
(which you can't do with a static class).
There are cases in which classes with no state can make use of
polymorphism, but I'm hard pressed to think of one in which a
_singleton_ class with no state can benefit from polymorphism.
As an example of a "singleton" that I wrote, I have data layer classes
that are singletons for each data table in the database: each data
table corresponds to exactly one data layer object. However, they all
inherit from DataHandler, which contains some generic code, and allows
me to write methods that accept and work with any DataHandler.
Technically speaking, these aren't singletons, but they're close enough
for me. I couldn't do this with static classes, because static classes
don't meaningfully participate in the class hierarchy.
However, for an example of a static class that has no business being a
singleton (and therefore isn't), take a look at System.Math in the .NET
Framework. It's just a collection of methods and constants, with no
state.
Arne Vajhøj wrote:
DBC User wrote:
I have a class with bunch of static methods. I could regourp all the
static methods into seperate 3 or 4 classes. I was thinking about using
Singlton pattern for all these 4 classes so that it behaves like static
still class. But my concern is, when going from static to singlton, I
need to add one more line to make sure the class is instantiated.
>
Am I going in right direction?
If the class contains static data, then I think moving
to Singleton is the right direction.
If the class only contains methods, then Singleton
does not make sense.
Arne