Search  
Friday, September 10, 2010 ..:: Articles » GOF Creational Patterns with C# ::..   Login
 Creational Patterns
Introduction | Factory | Abstract factory | Builder | Prototype | Singleton | Links
 
Show as single page

Singleton Pattern


The Singleton pattern is a specialist creational pattern as it's primary focus is to facilitate a single shared instance of our object rather than to decouple our client from the object's implementation as with the other creational patterns.

The pattern is useful when our design requires an object for which there must be only one instance that will be shared throughout the application. The point of the pattern is relieve the client of the task of ensuring that there is only one instance of this object. This will simplify the client by allowing it to focus upon the business intent rather than a mechanics issue. It will also avoid a potential client program bug where one reference to the object incorrectly allows another instance to be created. The following shows the client "creating" and using the singleton object.

  ShowUserCommentary(1);
  // call for a singleton instance. Since this is the first 
  // call this will trigger the creation of the instance.
  SingletonObject product1 = SingletonObject.Instance;
  // use the instance
  listBox1.AppendText(product1.SayWho());

  ShowUserCommentary(2);
  // call for a singleton instance again. We will get given 
  // the same instance
  SingletonObject product2 = SingletonObject.Instance;
  listBox1.AppendText(product2.SayWho());

This produces the following output from my demonstration program which shows the same singleton instance has been attached to both IProduct variables..

An implementation of the Singleton pattern typically involves the use of static variables, with the addition of synchronization if you want to be thread safe in a situation where it is possible that two threads will both make their initial access to the singleton at the same time. Here is a simpler thread safe implementation based upon ideas in an MSDN article I saw by Mark Townsend of Microsoft (see link at the end of this article). The instantiation of the SingletonObject class is triggered by the first reference to it's static Instance property. Since the SingletonObject 's class's constructor is not static, the static Instance property is initialised after the initialisation of the class which allows us to have the property return an instance of the class that contains it.

   // concrete Singleton
   public class SingletonObject {
       // fields
       private static readonly SingletonObject singletonObjectInstance = new SingletonObject();
       long _countUse = 1;
       // properties
       public static SingletonObject Instance {
              get {
                      return singletonObjectInstance;
              }
       }
       // constructor
       private SingletonObject() {}  // private, so cannot 
                                     // be used by a client

       // methods
       public string SayWho() {
              return String.Format("   * {0}: used {1} times\n",this.ToString(),_countUse++);
       }
   }

This implementation of the pattern is runtime efficient as we get a lazy load, meaning that the singleton object is only instantiated if our client actually executes a line of code which uses it's “Instance” property. However this lazy load feature is only assured if our Singleton class has no static members additional to the “Instance” property shown above. If we introduce additional static members we may think that they are available for use without triggering the overhead involved in the creation of an object, however this is not the case. Any use of a static member within a class will trigger the initialisation of all of the classes other static members, and in this case it will include the initialisation of our “Instance” property, which will in turn create the object even if the client session does not run through any code that will require the object.

There is a link at the bottom of this article pointing to an interesting technique, written by “davojc”, where he obtains singleton functionality via a .generic singleton provider implemented with .Net v2's Generics capability. This would allow us to have a class (eg. SomeNormalClass) offering the SayWho behaviour which would operate in a non-singleton manner, but if we accessed it as follows then we would get the singleton behaviour. This technique also avoids having to put the static field and property into each of our Singleton classes.

SingletonObject product1 = GenericSingletonProvider<SomeNormalClass>.Instance;

Here is my client demonstrating this option.

   ShowUserCommentary(3);
   /* Create a non-singleton object and use it. Repeat, and see 
    * that we have created a fresh object */
   SomeNormalClass product3 =  new SomeNormalClass();
   listBox1.AppendText(product3.SayWho());
   SomeNormalClass product4 = new SomeNormalClass();
   listBox1.AppendText(product4.SayWho());

   ShowUserCommentary(4);
   /* Now go through the same steps via a SingletonProvider 
   /* and see that we get, and reuse, just the one instance.*/
   SomeNormalClass product5 = 
         SingletonProvider<SomeNormalClass>.Instance;
   listBox1.AppendText(product5.SayWho());
   SomeNormalClass product6 = 
         SingletonProvider<SomeNormalClass>.Instance;
   listBox1.AppendText(product6.SayWho());






I won't repeat the implementation code here, but it is available from “davojc”s article, which can be accessed via my the links section at the bottom of this article, and it is also included in my demonstration program which is also available via my links section.


Prototype | Page 6 of 7 | Links

      

Copyright 2005 by Primos Computer Services   Terms Of Use  Privacy Statement