Implement Common Creational Design Patterns

Welcome to the next installment of the .NET Nuts & Bolts column. This article covers some creational design patterns and how to implement them using Microsoft .NET. It starts by exploring some of the common patterns and explaining why you should use them, followed by some simple examples. You’ll learn about a number of classes from different namespaces.

Definition of a Design Pattern

A design pattern is a solution for a common problem or issue. Design patterns are often associated with object-oriented programming, but they are not exclusive to it. In fact, even non-computing disciplines have concepts similar to design patterns, which is likely from where the programming community borrowed the concept.

A design pattern does not imply that only one solution to the problem exists, nor is it necessarily the best solution in all cases. Patterns merely provide a best-practice approach to a particular problem, learned from the countless experiences of the programming community. A pattern often has several variations. Each programmer must determine if and when to apply a particular pattern. Often, the programming environment in use influences the pattern choice. Not all programming environments and languages support all design patterns. What may be easy to create in one environment or language may be extremely difficult in another.

Patterns focus on many types of problems. Related patterns are grouped together and assigned a type. This helps programmers identify similar types and it simplifies the process of comparing similar patterns to find the appropriate one(s) to utilize. One such grouping is the creational design patterns: patterns focused on creating instances of objects. A class represents the definition of an object. An instance of an object is where the object/class has been created in memory, which in many languages is commonly done using the new keyword. This process is often referred to simply as instantiation.

Singleton Design Pattern

The singleton design pattern is focused on having one—and only one—instance of an object. It instills encapsulated control of the object from a common place. An example is a directory service. The directory may contain multiple types of entries, but you want only one instance of the actual directory through which all information is accessed and controlled.

Limit an Object to a Single Instance

When thinking about limiting an object to a single instance, the C# keyword static immediately comes to mind. A common misperception is that assigning static to the class will easily solve the problem. In actuality, because static cannot be applied at the class level, the solution is more complex. You must rely on the use of static within the class to create the desired behavior.

The first step is to create a class with a static member field and/or property to contain your internally stored data. The type of data you use dictates the field/property data type. An ArrayList or Hashtable is a common choice because it allows a dynamic number of objects to be stored and manipulated.

Next, prevent the object from being directly created by making all constructors private. This will allow you to restrict creation of all instances through a single method.

Finally, provide a static method for controlling access to your single instance.

Singleton Sample Code

The following sample code depicts how to implement the singleton design pattern in C#. It utilizes a GetInstance() static method to control a reference to the single instance of the class:

using System;
namespace CodeGuru.DesignPattern
{
   /// <summary>
   /// Class to demonstrate the use of the singleton design pattern.
   /// </summary>
   public class SingletonExample
   {
      /// <summary>Internal singleton instance</summary>
      private static SingletonExample _Singleton;

      /// <summary>
      /// Constructor to keep the class from being publicly instantiated.
      /// </summary>
      private SingletonExample()
      {
      }

      /// <summary>
      /// Control access to a single instance of the class.
      /// </summary>
      /// <returns></returns>
      public static SingletonExample GetInstance()
      {
         if( _Singleton == null )
         {
            _Singleton = new SingletonExample();
         }
         return _Singleton;
      }

      /// <summary>
      /// Use the instance to get some random data.
      /// </summary>
      /// <returns>Random data fetched from the instance.</returns>
      public int GetRandomInstanceData()
      {
         Random random = new Random();
         return random.Next();
      }
   }
}

Revised Singleton with a Controlled Load Sample Code

The above sample works great, as long as what you are trying to control access to is immediately available. What if loading the data from its source took some time? In the directory service example, the data contained within is likely to be thousands of rows of data that will not be instantly accessible. A time lag would occur from when you first tried to access the data to when it was ready for consumption.

You can work around this by adding a couple of status indicators that show whether the object currently is loaded or loading. Then, in the constructor, you call a method to initialize the object depending upon the status of its state indicators. If the object is loaded, no action is required. If the instance is not loaded or is currently being loaded, the method starts the loading process. If the object is loading, it will wait until it is loaded. Locking the class while it is loading allows the instance data to load without getting interrupted:

using System;
namespace CodeGuru.DesignPattern
{
   /// <summary>
   /// Class to demonstrate the use of the singleton design pattern.
   /// </summary>
   public class SingletonExample
   {
      /// <summary>Internal singleton instance</summary>
      private static SingletonExample _Singleton;

      /// <summary>Indicator if the object has been loaded.</summary>
      private static bool _IsLoaded = false;

      /// <summary>Indicator if the object is being loaded.</summary>
      private static bool _IsLoading = false;

      /// <summary>
      /// Constructor to keep the class from being publicly instantiated.
      /// </summary>
      private SingletonExample()
      {
         this.Initialize();
      }

      /// <summary>
      /// Control access to a single instance of the class.
      /// </summary>
      /// <returns></returns>
      public static SingletonExample GetInstance()
      {
         if( _Singleton == null )
         {
            _Singleton = new SingletonExample();
         }
         return _Singleton;
      }

      /// <summary>
      /// Use the instance to get some random data.
      /// </summary>
      /// <returns>Random data fetched from the instance.</returns>
      public int GetRandomInstanceData()
      {
         Random random = new Random();
         return random.Next();
      }

      /// <summary>
      /// Check if the data has been loaded and return the status.
      /// </summary>
      /// <returns></returns>
      private bool Initialize()
      {
         if( SingletonExample._IsLoaded )
         {
            // Data has already been loaded
            return true;
         }
         else if( SingletonExample._IsLoading )
         {
            while( SingletonExample._IsLoading )
            {
               // Block the calling thread for 50 milliseconds
               System.Threading.Thread.CurrentThread.Join(50);
            }
            return this.Initialize();
         }
         else
         {
            // Load the data
            this.LoadData();
            return this.Initialize();
         }
      }

      /// <summary>
      /// Load the data into the instance.
      /// </summary>
      private void LoadData()
      {
         lock(typeof(SingletonExample))
         {
            SingletonExample._IsLoaded  = false;
            SingletonExample._IsLoading = true;

            // Do something to load data here....

            SingletonExample._IsLoaded  = true;
            SingletonExample._IsLoading = false;
         }
      }
   }
}

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read