Geeks With Blogs
.NET Development and Design Gerardo Calderon

The singleton creation-pattern restricts an object of a class to a single instance. The class should expose a static instance that provides access to its public members and properties while guaranteeing thread-safety in a multi-threaded environment.  This pattern is typically implemented in scenarios where we have to cache static data and want to store it in a single location.

So how do we implement this pattern and which scenarios become good candidates?

Say we need to create a class that will load an application configuration file into memory and provide methods to retrieve the data. There might be multiple processes and assemblies that will be calling the class, therefore, it might be costly if we have to load the configuration file into memory every time we create an instance of the class. This is a perfect candidate for the singleton pattern. Since the configuration file will contain static data there is no need load it after the initial load.

Let's take a look at the following example. Suppose we have a class "Configuration".

public class Configuration
   public static readonly Configuration Instance = new Configuration();

   private Configuration() { }                      

   public string GetData()
      return "configuration data";

As you can see, we are exposing a static instance of the class. Out of the box, the static keyword takes care of two of our requirements. It ensures that the instance is created a single time and  the framework guarantees thread safety on static type initialization.  The readonly modifier restricts any calling code from modifying the instance once it has been initialized. In addition, we are implementing a private constructor to avoid accidental instantiation via the "new" operator.

The methods can then be accessed by calling the exposed public instance.

string configurationData = Configuration.Instance.GetData();




Posted on Monday, July 25, 2011 9:31 PM | Back to top

Comments on this post: The Singleton Approach

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © gerardosblog | Powered by: