Tuesday, November 16, 2010

The Singleton pattern in C#

Singleton Pattern:Example One
Thread safe example
It is created at the beginning of the application and this makes it thread safe.
The static part of the instance is private and the public Singleton can be gotten using GetInstance() that returns an instance of this class hence making sure that only one instance of the object is created in the application current state for example a shopping cart on a webpage.
using System;
 /// 
/// Thread-safe singleton  created at first call
/// 
namespace Singleton
{  

    
    class Singleton
    {
         private static Singleton instance = new Singleton();

         private Singleton(){}

          public static Singleton GetInstance()
          {
            return instance;
          }

          public double Total { get; set; }
          public string UserName { get; set; }
     }
 }


Here is how you make a call on the Singleton class :
Singleton single = Singleton.getInstance();
single.UserName = "Ngala" ;
single.Total = 345.00 ;
//....

Singleton pattern: Example Two
Lazy Evaluation example
With Lazy evaluation it means it is created in the memory when it is needed. When the class is created, it first make sure that it is not in the memory before creating a one. When it is created it is locked on a single thread.

using System;
 /// 
///  Lazy Evaluation example
/// 
namespace Singleton
{  

    class SingletonLazyEval
    { 
         private static SingletonLazyEval instance;

          private SingletonLazyEval() { }

          public static SingletonLazyEval GetInstance()
          {
              lock (typeof(SingletonLazyEval))
            {
              if (instance == null)
              {
                  instance = new SingletonLazyEval();
              }
              return instance;
            }
          }
        
    }
}

No comments:

Post a Comment

Machine learning is the future

I am very enthusiastic about machine learning and the potential it has solve tough problems. Considering the fact that the amount of data we...