Pages

Friday, April 19, 2013

Singleton Design Pattern C# Example

Singleton is one of the most frequently used Design Patterns in Software Engineering. You should apply Singleton pattern if you want to ensure that your class will have only one instance with a global point of access to it.

Let's look at Singleton code:
public sealed class Singleton
{
   private static readonly Singleton instance = new Singleton();
   
   private Singleton(){}

   public static Singleton GetInstance
   {
      get 
      {
         return instance; 
      }
   }
}
As you can see the code is pretty simple. Class is defined as sealed in order to prevent derivation. Also Singleton variable is marked readonly, which means that it can be assigned only during static initialization or in a constructor.
This approach has only one downside - it's not thread safe. This code must be improved if you work in multithreaded environment.

Saturday, April 6, 2013

Factory Design Pattern C# Example

Factory it's such a Design Pattern which defines an interface for creating an object, but lets the classes that implement the interface decide which class to instantiate. Factory Pattern lets a class postpone instantiation to sub-classes.

Let's see Factory Pattern in action on a simple example. Assume you have two different classes Toyota and Suzuki, they both implements abstract class Car. You need to instantiate one of these classes, but you don't know which of them, it depends on user. This is perfect scenario for the Factory Pattern.

Factory Design Pattern example program diagram