Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Singleton Pattern?

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.

like image 212
yogesh Avatar asked Jul 30 '11 13:07

yogesh


1 Answers

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.

Edit

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.

like image 181
Anders Abel Avatar answered Sep 29 '22 06:09

Anders Abel