CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

follow us on Twitter

Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

Become a Marketplace Partner

jobs.internet.com

internet.commerce
Partners & Affiliates
















Home >> Columns >> .NET Nuts & Bolts


Implement Common Creational Design Patterns
Rating:

Mark Strawmyer (view profile)
July 7, 2004

Go to page: 1  2  Next

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


(continued)



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;
         }
      }
   }
}

About the Author
Mark Strawmyer, MCSD, MCSE, MCDBA is a Senior Architect of .NET applications for large and mid-size organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in architecture, design and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C#. You can reach Mark at mstrawmyer@crowechizek.com.

Go to page: 1  2  Next

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed







RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
No Comments Posted.
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Whitepapers and eBooks

Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
IBM Solutions Brief: Go Green With IBM System xTM And Intel
HP eBook: Simplifying SQL Server Management
IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
Microsoft PDF: Top 10 Reasons to Move to Server Virtualization with Hyper-V
Microsoft PDF: Six Reasons Why Microsoft's Hyper-V Will Overtake Vmware
Microsoft Step-by-Step Guide: Hyper-V and Failover Clustering
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Microsoft PDF: Top 11 Reasons to Upgrade to Windows Server 2008
Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
  PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
Go Parallel Article: Q&A with a TBB Junkie
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
IBM eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
HP eBook: Guide to Storage Networking
MORE WHITEPAPERS, EBOOKS, AND ARTICLES