开发者

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开发者_Go百科 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.

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.


C# uses the static keyword to implement a singleton. However, the virtue of that keyword alone doesn't truly implement the pattern.

Consider this:

public class MyFoo
{
  public static MyBar;
}

Is MyBar a singleton? That particular instance of it is static, but the class itself isn't a singleton because it doesn't prevent you from creating more instances of it. To implement the singleton pattern you'd need the class itself to guarantee that there can be one and only one instance of it. Something more like this:

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}

Reference here.

With this implementation, the application can't create multiple instances of this class. This is very useful for things where the singleton pattern applies, such as a factory class which builds/tracks instances of other classes. (An IoC container, for example.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜