September 24
During an internal .NET 101 training at Microsoft one of my students asked a very interesting question: why would we choose to use a
Singleton design pattern instead of simply using a "global" static class?
After some thinking and investigation, here are my conclusions of the benefits for sticking with Singletons:
- Singletons are objects and it might be more intuitive to deal with them for state manipulation rather than through the use of static fields in static classes.
- In the same line, you can't pass a static class as parameter, while no such limitation exists for the Singleton object.
- Static classes cannot implement interfaces. The class that defines the Singleton can.
- The global static class can be loaded too early, consuming valuable application resources, while the Singleton supports lazy allocation where an instance is created only as needed.
- Static classes do not benefit from default serialization mechanisms.
BR,
-- AFurtado