I am .NET developer. I had several times interviewed and many times I encountered with a question that "What is the real-world use of Singleton Design pattern?". But my question is "Why we use singleton, static keyword is sufficient?" because the objective of singleton design pattern is to prevent creating double instances. If I mark my single_class as static I can also achieve the same objective or not.
The ability in C# to make classes static is a language implementation of the singleton pattern.
Design patterns are common ways to solve common problems. In a language such as C++ where classes cannot be marked static directly, a singleton has to be implemented by some smart construct - a pattern. In C# that functionality is built in through static classes.
The next part of the question/discussion is where it is appropriate to use singletons, which are a kind of global object/variable. I assume that the interviewers want to have some discussion on where it is appropriate and not.
Reading Jon Skeet's answer to the question dave linked to I'd like to add another thing:
A static class cannot implement interfaces, so if there is a need to have a singleton that implements a specific interface it has to be a real object and marking the class as static
won't do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With