8

Singleton implemented with C# could be like:

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

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

If I use static to implement it like:

public static class Globals{
  public static Singleton Instance = new Singleton();
}

in this way, app should also only get the one instance for the entire app. So what's the difference between these 2 approaches? Why not use static member directly(more simple and straight forward)?

KentZhou
  • 24,805
  • 41
  • 134
  • 200

2 Answers2

9

If you use the second approach:

public static class Globals{
  public static Singleton Instance = new Singleton();
}

There's nothing preventing somebody from doing:

Singleton anotherInstance = new Singleton(); // Violates singleton rules

You also don't get the same lazy initialization your first version (attempts to) achieve, plus you're using a public field, which doesn't allow you the same flexibility in the future if you need to change what happens when a value is fetched.

Note that .NET 4 provides a potentially better approach to making a singleton:

public class Singleton
{
   private static readonly Lazy<Singleton> instance = new Lazy<Singleton>( ()=> new Singleton());

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         return instance.Value;
      }
   }
}

This is nice because it's fully lazy and fully thread safe, but also simple.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Do we need to declare *static constructor* in here for thread-safe? – cuongle Oct 01 '12 at 17:56
  • @CuongLe Not with the `Lazy` version. It's very nice in that it provides the proper thread safety AND perfect lazy instantiation, with a simple API. – Reed Copsey Oct 01 '12 at 17:56
  • 1
    Not to mention that, in the original post, the public static "Instance" is not readonly, so I could write "Globals.Instance = null;" anytime ! – Alexandre Vinçon Oct 01 '12 at 18:37
-1

Below are some differences between static and Singleton :

  1. Singleton is a pattern while static is a keyword.
  2. Singleton class can have static and non static method, but static class can have only static members and methods.
  3. We can implement interface in a Singleton class but in static class we cannot implement interface.
  4. We can extend the Singleton class while we static class we can’t, i.e. Singleton class can be derived from any type of class.

for more static vs Singleton

Community
  • 1
  • 1
Vijjendra
  • 24,223
  • 12
  • 60
  • 92