When would a singleton actually be easier or better than a static class? It seems to me creating a singleton is just extra effort that’s not actually needed, but I’m sure there is a good reason. Otherwise, they wouldn’t be used, obviously.
Share
One good reason for preferring a singleton over a static class (assuming you have no better patterns at your disposal 😉 ), is swapping out one singleton instance with another.
For example, if I have a logging class like this:
It works really well, but what if Logger writes things to a database, or writes output to the console. If you’re writing tests, you probably don’t want all those side-effects — but since the log method is static, you can’t do anything except.
Ok, so I want to hot-swap my Log method for testing. Go go gadget singleton!
So you can define a
TestLogger : Loggerwith an emptyLogmethod, then set an instance of your test logger to the singleton instance for tests. Presto! You can hotswap your logger implementation for tests or production without affecting client code.