Using the Singleton Pattern

Posted by Jack Altiere on March 26th, 2008

Chances are if you’ve heard of any design pattern, it’s this one.  There seems to be a lot of negative comments concerning the singleton pattern.  I’ve heard of it referred to as nothing but a global variable, and I’ve also heard that using a singleton in the first place is poor design.  I’m going to have to agree to disagree with these people.  I will agree that this pattern is often overused, but in my opinion it has it’s uses. 

The singleton design pattern is actually a pretty simple concept.   It just means that you are restricting the instantiation of a class to a single instance.    Before we get into the implementation of the pattern, let’s figure out why we would use it. This pattern should be used when you need one and only one instance of a class.   In my opinion, one of the biggest mistakes people make is implementing this pattern because they “only need 1 instance”.  If this is why you chose this pattern, then chances are that there is a better way to design your application.   The question you should be asking yourself is, “Will something VERY VERY bad happen if there is more than 1 instance?”

   1: namespace Singleton
   2: {
   3:    public sealed class Foo
   4:    {
   5:       // This is the instance to our class.
   6:       static Foo _instance = null;
   7:       
   8:       // A private constructor means that it can't
   9:       // be instantiated from outside the class.
  10:       private Foo()
  11:       {
  12:  
  13:       }
  14:  
  15:       // This property allows us to get access
  16:       // to the singleton. It only creates a 
  17:       // new instance the first time.
  18:       public static Foo Instance
  19:       {
  20:          get
  21:          {
  22:             if (_instance == null)
  23:                _instance = new Foo();
  24:  
  25:             return _instance;
  26:          }
  27:       }
  28:    }
  29: }

Above is one possible implementation of the singleton pattern.  Notice, our class Foo is sealed, because I don’t want to allow anyone to inherit from it.  I made the constructor private, this means that you will not be able to create an instance of this class with the new operator when you use it.  Instead, to get an instance of the class you need to go through the property.  That is the key to implementing this pattern.  You need to control instantiation through either a property or a method.  (I chose to use a property) This is an example of how you would get an instance to Foo:

   1: namespace Singleton
   2: {
   3:    class Program
   4:    {
   5:       static void Main(string[] args)
   6:       {
   7:          // Get the instance to our singleton.
   8:          Foo foo1 = Foo.Instance;
   9:       }
  10:    }
  11: }

I needs to be pointed out though, our implementation of the singleton pattern has a big problem that may not be apparent.   It is not thread safe, meaning that if you were to try to get instances from multiple threads, you could get multiple instances rather than the one instance which is our goal.  This is a pretty easy obstacle to overcome in C# using locking.  Making this change makes our singleton thread safe:

   1: namespace Singleton
   2: {
   3:    public sealed class Foo
   4:    {
   5:       // This is the instance to our class.
   6:       static Foo _instance = null;
   7:  
   8:       // This will serve as a lock to make our 
   9:       // singleton thread safe.
  10:       static readonly object _mutex = new object();
  11:       
  12:       // A private constructor means that it can't
  13:       // be instantiated from outside the class.
  14:       private Foo()
  15:       {
  16:  
  17:       }
  18:  
  19:       // This property allows us to get access
  20:       // to the singleton. It only creates a 
  21:       // new instance the first time.
  22:       public static Foo Instance
  23:       {
  24:          get
  25:          {
  26:             // This lock allows thread safety.
  27:             lock (_mutex)
  28:             {
  29:                if (_instance == null)
  30:                   _instance = new Foo();
  31:  
  32:                return _instance;
  33:             }
  34:          }
  35:       }
  36:    }
  37: }

So now we have our singleton, how do know for sure that we’re only getting 1 instance?  I put together a quick test to prove exactly that.  First, I modified the Foo class so that is has a GUID variable that is assigned when the instance is created.   The reasoning for this is that if we get the same GUID back every time I load the SingleCheck property I must have the same instance back, since generating 2 identical GUID’s is impossible.

   1: namespace Singleton
   2: {
   3:    public sealed class Foo
   4:    {
   5:       // This is the instance to our class.
   6:       static Foo _instance = null;
   7:  
   8:       // This will serve as a lock to make our 
   9:       // singleton thread safe.
  10:       static readonly object _mutex = new object();
  11:       static Guid _singleCheck;
  12:       
  13:       // A private constructor means that it can't
  14:       // be instantiated from outside the class.
  15:       private Foo()
  16:       {
  17:  
  18:       }
  19:  
  20:       // This property allows us to get access
  21:       // to the singleton. It only creates a 
  22:       // new instance the first time.
  23:       public static Foo Instance
  24:       {
  25:          get
  26:          {
  27:             // This lock allows thread safety.
  28:             lock (_mutex)
  29:             {
  30:                if (_instance == null)
  31:                {
  32:                   _instance = new Foo();
  33:                   _singleCheck = System.Guid.NewGuid();
  34:                }
  35:  
  36:                return _instance;
  37:             }
  38:          }
  39:       }
  40:  
  41:       public Guid SingleCheck
  42:       {
  43:          get { return _singleCheck; }
  44:       }
  45:    }
  46: }

After I had the singleton ready, I created a console application that creates a few instances to Foo, and threw in a couple BackgroundWorker objects to test some threading. 

   1: namespace Singleton
   2: {
   3:    class Program
   4:    {
   5:       static void Main(string[] args)
   6:       {
   7:          // Get the instance to our singleton.
   8:          Foo foo1 = Foo.Instance;
   9:          Foo foo2 = Foo.Instance;
  10:          Foo foo3 = Foo.Instance;
  11:          Foo foo4 = Foo.Instance;
  12:  
  13:          Console.WriteLine("foo1: " + foo1.SingleCheck.ToString());
  14:          Console.WriteLine("foo2: " + foo2.SingleCheck.ToString());
  15:          Console.WriteLine("foo3: " + foo3.SingleCheck.ToString());
  16:          Console.WriteLine("foo4: " + foo4.SingleCheck.ToString());
  17:  
  18:          // Check threading.
  19:          BackgroundWorker worker1 = new BackgroundWorker();
  20:          BackgroundWorker worker2 = new BackgroundWorker();
  21:          worker1.DoWork += new DoWorkEventHandler(doThreadWork1);
  22:          worker2.DoWork += new DoWorkEventHandler(doThreadWork2);
  23:          worker1.RunWorkerAsync();
  24:          worker2.RunWorkerAsync();
  25:  
  26:          Console.ReadLine();
  27:       }
  28:  
  29:       static void doThreadWork1(object sender, DoWorkEventArgs e)
  30:       {
  31:          Foo threadFoo = Foo.Instance;
  32:          Console.WriteLine("threaded (1): " + threadFoo.SingleCheck.ToString());
  33:       }
  34:       static void doThreadWork2(object sender, DoWorkEventArgs e)
  35:       {
  36:          Foo threadFoo = Foo.Instance;
  37:          Console.WriteLine("threaded (2): " + threadFoo.SingleCheck.ToString());
  38:       }
  39:  
  40:    }
  41: }

This was the output of my test, it shows that we were getting the same instance back each time.

There is one last thing I’d like to touch on concerning the use of this pattern.   Remember the golden rule…..requirements change.   Even though when you created your singleton it was absolutely necessary, a year from now your application may change and the use of a singleton is no longer necessary.  You can use this pattern in your code in a way that minimizes the impact of a change like this.

   1: // Control places in the code that
   2: // get the instance of Foo.
   3: Foo myFoo = Foo.Instance;
   4:  
   5: // That way you can treat it like a normal
   6: // object when you use it.  This makes a change
   7: // easier since you only have to worry about the 
   8: // declaration.
   9: myFoo.DoSomething();
  10: myFoo.DoSomethingElse();
  11:  
  12: // This syntax is valid and will work,
  13: // but it makes a change harder because 
  14: // there are more places in your code
  15: // that depend on Foo being a Singleton.
  16: Foo.Instance.DoSomething();
  17: Foo.Instance.DoSomethingElse();

Hopefully now you have a grasp on what the singleton design pattern is, and how to implement it.  I’ll leave you with this piece of advice, because this design pattern is definitely overused.  Don’t let everything start to look like a nail just because you have a hammer!

kick it on DotNetKicks.com

Using the Factory Pattern

Posted by Jack Altiere on December 4th, 2007

A friend of mine asked me an interesting question the other day.  He wanted some help coming up with a solution to a problem he was running into.  Here is the short version of the problem requirements:

  1. He had an abstract class and several derived classes.
  2. His derived classes were to be serialized as XML on the file system, and he wanted to instantiate them at run time.
  3. He wouldn’t know until run time which derived class he was dealing with.

He was using C++ and he eventually came up with a good solution to the problem, but it got me wondering how I would handle the same requirements using C#.  This sounded like a tailor made case for the factory design pattern, so I decided to give it a shot and see where it led.

The factory design pattern is a creational design pattern, which basically means that it deals with the creation of objects.  It allows you to create an object at design time without really knowing what type of object you are really dealing with.  Confused?  How about a simple example.

   1: // We have an abstract class Product 
   2: // that has 2 derived classes --
   3: // ProductA and ProductB   
   4: public abstract class Product{}   
   5: public class ProductA : Product{}   
   6: public class ProductB : Product{}   
   7:     
   8: // If we do it this way at design time
   9: // we can't change the type of object    
  10: // instantiated without recompiling the application.    
  11: // The variable prod will always be of type ProductA   
  12: ProductA prod = new ProductA();

I want to avoid making the decision about what time of object to instantiate until run time, which is where the factory pattern comes in.  Another of our requirements is that the objects be serializeable into XML files.  For my example, I created an abstract class that I called BaseFilter, and 2 derived classes called AddFilter and MultiplyFilter.  I wanted to use an example that would be easy to understand when I put this together.  Here are my class definitions:

   1: public abstract class BaseFilter
   2: {
   3:    public abstract int NumberOperation(int number1, int number2);
   4: }
   5:  
   6: public class AddFilter : BaseFilter
   7: {
   8:    public override int NumberOperation(int number1, int number2)
   9:    {
  10:       return number1 + number2;
  11:    }
  12: }
  13:  
  14: public class MultiplyFilter : BaseFilter
  15: {
  16:    public override int NumberOperation(int number1, int number2)
  17:    {
  18:       return number1 * number2;
  19:    }
  20: }

Now, I need to address the idea of serialization for these classes, so I marked the derived classes with the [Serializable()] Attribute, and I used XMLInclude in my abstract class to allow me to deserialize my objects.  The final version of my classes looks like this:

   1: [System.Xml.Serialization.XmlInclude(typeof(MultiplyFilter))]
   2: [System.Xml.Serialization.XmlInclude(typeof(AddFilter))]
   3: public abstract class BaseFilter
   4: {
   5:    public abstract int NumberOperation(int number1, int number2);
   6: }
   7:  
   8: [Serializable()]
   9: public class AddFilter : BaseFilter
  10: {
  11:    public override int NumberOperation(int number1, int number2)
  12:    {
  13:       return number1 + number2;
  14:    }
  15: }
  16:  
  17: [Serializable()]
  18: public class MultiplyFilter : BaseFilter
  19: {
  20:    public override int NumberOperation(int number1, int number2)
  21:    {
  22:       return number1 * number2;
  23:    }
  24: }

Now that I have my classes defined, I nned to think about how to implement my factory pattern here.  My factory class will also control the deserialization of the XML files.  My factory class ended up looking like this:

   1: public class FilterFactory
   2: {
   3:    private BaseFilter _filter;
   4:    
   5:    public FilterFactory()
   6:    {
   7:  
   8:    }
   9:    
  10:    public void ReadFile(string fileName)
  11:    {
  12:       if (!File.Exists(fileName))
  13:          throw new Exception("Error: File does not exist.");
  14:  
  15:       using (FileStream fStream = new FileStream(fileName, FileMode.Open))
  16:       {
  17:          XmlSerializer serializer;
  18:          serializer = new XmlSerializer(typeof(BaseFilter));
  19:          _filter = (BaseFilter)serializer.Deserialize(fStream);
  20:       }
  21:    }
  22:    
  23:    public int NumberOperation(int number1, int number2)
  24:    {
  25:       return _filter.NumberOperation(number1, number2);
  26:    }
  27: }

To put it all together, I wrote a small console application that tested all this.

   1: class Program
   2: {
   3:    static void Main(string[] args)
   4:    {
   5:       // Create a sample serialized multiply filter.
   6:       using (FileStream fStream = 
   7:          new FileStream("multiply.xml", FileMode.Create))
   8:       {
   9:          MultiplyFilter mFilter = new MultiplyFilter();
  10:          XmlSerializer serializer = new XmlSerializer(typeof(BaseFilter));
  11:          serializer.Serialize(fStream, mFilter);
  12:       }
  13:  
  14:       // Create a sample serialized add filter.
  15:       using (FileStream fStream = 
  16:          new FileStream("add.xml", FileMode.Create))
  17:       {
  18:          AddFilter aFilter = new AddFilter();
  19:          XmlSerializer serializer = new XmlSerializer(typeof(BaseFilter));
  20:          serializer.Serialize(fStream, aFilter);
  21:       }
  22:  
  23:       // Get an instance to my factory.
  24:       FilterFactory factory = new FilterFactory();
  25:  
  26:       factory.ReadFile("multiply.xml");
  27:       Console.WriteLine("Answer for 5 and 2 is: {0}", 
  28:          factory.NumberOperation(5, 2));
  29:  
  30:       Console.WriteLine(System.Environment.NewLine);
  31:  
  32:       factory.ReadFile("add.xml");
  33:       Console.WriteLine("Answer for 5 and 2 is: {0}", 
  34:          factory.NumberOperation(5, 2));
  35:  
  36:       Console.WriteLine(System.Environment.NewLine);
  37:       Console.WriteLine("Press any key to continue.");
  38:       Console.ReadKey();
  39:    }
  40: }
 

In the console application, the first thing I did was created a sample filter for both of my supported operations and then serialzed them.  This doesn’t necessarily make sense in a real world example, but it works for the sake of this example.  Then I created a factory instance, which allowed me to create instances of either type I wanted at run time.  To do this, my factory class reads the XML file, and deserializes it, which all happens in the ReadFile function.  To prove that I had the correct derived instances,  I called the NumberOperation method.  The factory created an instance of the correct derived class in each case based on the results of the deserialization.  The output of this console application looked like this:

output

That works as advertised, but there was one thing about this solution that I didn’t care for.  Astute readers will notice that I had to use the XMLInclude directive on my abstract class.  This basically says that when a BaseFilter is deserialized, it could actually be a MultiplyFilter or an AddFilter.  This means that if I added a SubtractFilter I would have to modify the base class to account for the new type so that it could be deserialized.  What happens if the abstract definition was in an assembly that I didn’t have the source for?  I’ll have to put some brain cells on that one when I get some time and see if I can come up with a solution.

kick it on DotNetKicks.com

Downloads

Twitter Updates

    Top Commentators

    • No commentators.

    Copyright © 2007 Jack Altiere. All rights reserved.