December 08, 2003

C# Patterns

There has been a lot of discussion on applying Design Patterns to the C# language. I found many useful links on the C2 Wiki entitled CsharpPatterns .

The point of this article is to explore how C# langauge features can be leveraged when implementing patterns. I’ll start with a few examples in C++ and Java before I describe some of the advances available in C#.

The Singleton Pattern , for instance, is commonly implemented C++ as:

class Singleton {
 public:
     Singleton() {}
     Singleton& getInstance() {
          static Singleton singleton;
          return singleton;
      }
 protected:
     Singleton() {}
};

The approach is very explicit in it’s aim to create the first instance of the singleton with it’s first use (a call to getInstance()). This approach could have serious problems in a multithreaded environment as two pieces of code on two different threads might be able to create two instances of the singleton. A simple workaround would be to instantiate your singletons before your threads start up…

In Java, many applications choose to use the double-checked locking mechanism as illustrated by the following example:

// Broken multithreaded version
// "Double-Checked Locking" idiom
class Foo { 
   private Helper helper = null;
   public Helper getHelper() {
      if (helper == null) 
        synchronized(this) {
           if (helper == null) 
             helper = new Helper();
         }    
      return helper;
      }
   // other functions and members...
   }

You can plainly see that Java enables synchronization with the synchronized keyword. However, the article that the code was copied from explains how this approach is flawed. Read the article for the full discussion.

Consider this almost trivial implementation of the Singleton Pattern in C#:

// .NET Singleton
sealed class Singleton {
     private Singleton() {}
     public static readonly Singleton Instance = new Singleton();
}

This approach is also possible in Java, but there is a subtle difference in the two implementations. In Java, the singleton gets instantiated when the class is loaded. In C#, the singleton gets instantiated the first time the Singleton member is accessed (much like static allocation in C++), lazy instantiation.

In addition, the .NET Framework guarantees the thread-safe initialization of static members. This is a common task that’s finally automated and enforced by powers other than our own diligence. I welcome that.

The sealed class modifier is used to prevent Singleton subclassing, something the GoF describe as dubious and prone to error.

Credits:

Exploring the Singleton Design Pattern by Mark Townsend
The C2 Wiki

Posted by Nick Codignotto at December 8, 2003 09:00 AM
Posted to Programming
Comments
Post a comment









Remember personal info?






Valid XHTML 1.0!   Valid CSS!