Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between static property and singleton?

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)?

like image 615
KentZhou Avatar asked Oct 01 '12 17:10

KentZhou


1 Answers

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.

like image 139
Reed Copsey Avatar answered Nov 04 '22 04:11

Reed Copsey