Creational Design Pattern for .NET

This article discusses the creational design pattern concepts and how to implement it in your applications using C# and .NET.

Design Pattern: Design Patterns are a reusable, high quality solution to a given requirement, task or recurring problem and are commonly defined as time-tested solutions. So basically you have a problem context and the proposed solution for the same.  Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.

Design patterns have two major benefits.

  1. They provide you with a way to solve issues related to software development using a proven solution.
  2. Design patterns make communication between designers more efficient.
They are categorized in three groups:

CREATIONAL1.gif

Let's have a look at the Creational Design Pattern:

CREATIONAL: The Creational Design Pattern deals with object creation mechanisms; trying to create objects in a manner suitable to the situation. It focuses on how the objects are created and utilized in an application. The Creational Design Pattern deals with object creation mechanisms, trying to create objects in a manner suitable to the situation.

The Creational Design Pattern is divided into the five categories:
 
CREATIONAL2.gif    

Factory Method: The Factory method takes care of one product whereas the abstract factory pattern provides a way to encapsulate a family of products. This pattern is used to create concrete class instances without specifying the exact class type. We can say it is an Object creation pattern also. Here objects are created without knowing the class of the object. So basically the factory pattern is used wherever the sub classes are given the previledge of instantiating a method that can create an object.

Model:
 
CREATIONAL3.gif

UML Diagram:

CREATIONAL4.gif 

Example:

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
FactoryMethod
{

   
class Example

   
{

       
static void Main()

       
{
            // constructors call Factory Method

            File
[] Files = new File[2];
            Files[0] = new Furniture();

            Files[1] = new Crokery();

           
foreach (File File in Files)

           
{

               
Console.WriteLine("\n" + File.GetType().Name + "--");

               
foreach (Items Items in File.Itemss)

               
{

                   
Console.WriteLine(" " + Items.GetType().Name);

     
          }

           
}

           
Console.ReadKey();

       
}

    }

   
// The 'Product' abstract class

   
abstract class Items

   
{        }
    // ConcreteProduct classes

    
class SofasetItems : Items

   
{        }

    
class PlatesItems : Items

   
{        }

    
class BedItems : Items

   
{        }

    
class GlassesItems : Items

   
{        }

    
class TeasetItems : Items

   
{        }

    
class BowlsItems : Items

   
{        }

    
class DiningItems : Items

   
{        }

  
abstract class File

   
{

    
private List<Items> _Itemss = new List<Items>();
      // Constructor calls abstract Factory method

      
public File()

       
{

         
this.CreateItemss();

       
}

      
public List<Items> Itemss

       
{

         
get { return _Itemss; }

       
}
      // Factory Method

      
public abstract void CreateItemss();

   
}

  
class Furniture : File

   
{
      // Factory Method implementation

     
public override void CreateItemss()

       
{

         
Itemss.Add(new SofasetItems());

         
Itemss.Add(new BedItems());

         
Itemss.Add(new DiningItems());

       
}

    
}

 
class Crokery : File

   
{

     
public override void CreateItemss()

       
{

         
Itemss.Add(new PlatesItems());

         
Itemss.Add(new GlassesItems());

         
Itemss.Add(new TeasetItems());

         
Itemss.Add(new BowlsItems());

       
}

   
}

}


ABSTRACT FACTORY: Provides an interface for creating families of relegated or dependent objects without specifying their concrete classes.

There are two types of Abstract Factories:
  • The simple Abstract Factory is an abstract class defining Factory methods to answer instances of concrete subclasses
  • The second form of Abstract Factory is an abstract class defining a common protocol of Factory methods.
Model:

CREATIONAL5.gif 

UML Diagram:
    
CREATIONAL6.gif    

Example:

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;

namespace
AbstractFactory
{

   
class Example

   
{

   
public static void Main()

   
{

     
ContinentFactory africa = new AfricaFactory();

     
AnimalWorld world = new AnimalWorld(africa);

     
world.RunFoodChain();

     
ContinentFactory america = new AmericaFactory();

     
world = new AnimalWorld(america);

     
world.RunFoodChain();

     
Console.ReadKey();

   
}

}

abstract class ContinentFactory

 
{

   
public abstract Herbivore CreateHerbivore();

   
public abstract Carnivore CreateCarnivore();

 
}

 
class AfricaFactory : ContinentFactory

 
{

   
public override Herbivore CreateHerbivore()

   
{

     
return new Wildebeest();

   
}

   
public override Carnivore CreateCarnivore()

   
{

     
return new Lion();

   
}

 
}

 
class AmericaFactory : ContinentFactory

 
{

   
public override Herbivore CreateHerbivore()

   
{

     
return new Bison();

   
}

   
public override Carnivore CreateCarnivore()

   
{

     
return new Wolf();

   
}

 
}

abstract class Herbivore

 
{     }

 
abstract class Carnivore

 
{

  
public abstract void Eat(Herbivore h);

 
}

 
class Wildebeest : Herbivore

 
{     }

class Lion : Carnivore

 
{

  
public override void Eat(Herbivore h)

   
{

    
Console.WriteLine(this.GetType().Name +

       
" eats " + h.GetType().Name);

   
}

 
}

class Bison : Herbivore

 
{     }

 
class Wolf : Carnivore

 
{

   
public override void Eat(Herbivore h)

   
{

     
Console.WriteLine(this.GetType().Name +

       
" eats " + h.GetType().Name);

   
}

 
}

 
class AnimalWorld

 
{

   
private Herbivore _herbivore;

   
private Carnivore _carnivore;

   
public AnimalWorld(ContinentFactory factory)

   
{

     
_carnivore = factory.CreateCarnivore();

     
_herbivore = factory.CreateHerbivore();

   
}

   
public void RunFoodChain()

   
{

     
_carnivore.Eat(_herbivore);

   
}

 
}

}

BUILDER: The Builder pattern helps us to separate the construction of a complex object from its representation so that the same construction process can create different representations. The Builder pattern is useful when the construction of the object is very complex. The main objective is to separate the construction of objects and their representations.

Model:

CREATIONAL7.gif 

UML Diagram:

CREATIONAL8.gif    

Example:

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;

namespace
Celebrities
{

   
class Program

   
{

    
public static void Main()

     
{

     
BollywoodCelebrities Celebrities;

     
Nominated Nominated = new Nominated();

     
Celebrities = new KaterinaCelebrities();

     
Nominated.Construct(Celebrities);

     
Celebrities.Bollywood.Show();

     
Celebrities = new ShahrukhCelebrities();

     
Nominated.Construct(Celebrities);

     
Celebrities.Bollywood.Show();

     
Celebrities = new AshwaryaCelebrities();

     
Nominated.Construct(Celebrities);

     
Celebrities.Bollywood.Show();

     
Console.ReadKey();

      
}

    
}

class Nominated

 
{

    
public void Construct(BollywoodCelebrities bollywoodCelebrities)

   
{

     
bollywoodCelebrities.Height();

     
bollywoodCelebrities.RecentMovie();

     
bollywoodCelebrities.Awards();

   
}

 
}

 
abstract class BollywoodCelebrities

 
{

   
protected Bollywood bollywood;

   
public Bollywood Bollywood

    
{

     
get { return bollywood; }

    
}

   
public abstract void Height();

   
public abstract void RecentMovie();

   
public abstract void Awards();

 
}

class AshwaryaCelebrities : BollywoodCelebrities

 
{

   
public AshwaryaCelebrities()

    
{

     
bollywood = new Bollywood("Ashwarya");

    
}

   
public override void Height()

    
{

     
bollywood["Height"] = "5ft 8 inches ";

    
}

   
public override void RecentMovie()

    
{

     
bollywood["RecentMovie"] = "Guzarish";

    
}

   
public override void Awards()

    
{

     
bollywood["Awards"] = "3";

    
}

 
}

class ShahrukhCelebrities : BollywoodCelebrities

 
{

   
public ShahrukhCelebrities()

    
{

     
bollywood = new Bollywood("Shahrukh");

    
}

   
public override void Height()

    
{

     
bollywood["Height"] = "5ft 6inches";

    
}

   
public override void RecentMovie()

    
{

     
bollywood["RecentMovie"] = "My Name is Khan";

    
}

   
public override void Awards()

    
{

     
bollywood["Awards"] = "4";

    
}

 
}

class KaterinaCelebrities : BollywoodCelebrities

 
{

   
public KaterinaCelebrities()

    
{

     
bollywood = new Bollywood("Katerina");

    
}

   
public override void Height()

    
{

     
bollywood["Height"] = "6ft";

    
}

   
public override void RecentMovie()

    
{

     
bollywood["RecentMovie"] = "Tees Maar Khan";

    
}

   
public override void Awards()

   
{

    
bollywood["Awards"] = "1";

   
}

 
}

class Bollywood

 
{

   
private string _BollywoodCel;

   
private Dictionary<string,string> _parts =

   
new Dictionary<string,string>();

   
public Bollywood(string BollywoodCel)

     
{

 
      this._BollywoodCel = BollywoodCel;

     
}

   
public string this[string key]

     
{

      
get { return _parts[key]; }

      
set { _parts[key] = value; }

     
}

   
public void Show()

     
{

      
Console.WriteLine("\n---------------------------");

      
Console.WriteLine(" Bollywood Celebrity: {0}", _BollywoodCel);

      
Console.WriteLine(" Height : {0}", _parts["Height"]);

      
Console.WriteLine(" RecentMovie : {0}", _parts["RecentMovie"]);

      
Console.WriteLine(" **Awards**: {0}", _parts["Awards"]);

     
}

 
}

}


PROTOTYPE: The prototype design pattern is a design pattern that is used to instantiate a class by copying, or cloning, the properties of an existing object. The new object is an exact copy of the prototype but permits modification without altering the original. This is a creational pattern as it is used to control class instantiation and object generation. The pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a brand new object, using the new operator, is inefficient.

Model:

CREATIONAL9.gif    

UML Diagram:

CREATIONAL10.gif    

Example:

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
Prototype
{

   
class Example

   
{

    
static void Main()

   
{

    
ColorManager colormanager = new ColorManager();

    
colormanager["red"] = new Color(255, 0, 0);

    
colormanager["green"] = new Color(0, 255, 0);

    
colormanager["blue"] = new Color(0, 0, 255);

    
colormanager["angry"] = new Color(255, 54, 0);

    
colormanager["peace"] = new Color(128, 211, 128);

    
colormanager["flame"] = new Color(211, 34, 20);

    
Color color1 = colormanager["red"].Clone() as Color;

    
Color color2 = colormanager["peace"].Clone() as Color;

    
Color color3 = colormanager["flame"].Clone() as Color;

    
Console.ReadKey();

   
}

 
}

 
abstract class ColorPrototype

 
{

   
public abstract ColorPrototype Clone();

 
}

 
class Color : ColorPrototype

 
{

   
private int _red;

   
private int _green;

   
private int _blue;

 
public Color(int red, int green, int blue)

   
{

     
this._red = red;

     
this._green = green;

     
this._blue = blue;

   
}

 
public override ColorPrototype Clone()

   
{

     
Console.WriteLine(

       
"Cloning color RGB: {0,3},{1,3},{2,3}",

        
_red, _green, _blue);

      
return this.MemberwiseClone() as ColorPrototype;

   
}

 
}

 
class ColorManager

 
{

   
private Dictionary<string, ColorPrototype> _colors =

   
new Dictionary<string, ColorPrototype>();

   
public ColorPrototype this[string key]

   
{

     
get { return _colors[key]; }

     
set { _colors.Add(key, value); }

   
}

 
}

}

SINGLETON: The singleton pattern is useful when a single, global point of access to a limited resource is required. It is more appropriate than creating a global variable as this may be copied, leading to multiple access points and the risk that the duplicates become out of step with the original. It focuses on how the object is created and ensures that there exists only one instance of the object.

Model:

CREATIONAL11.gif
 
UML Diagram:
    
CREATIONAL12.gif    

Example:

using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace
Singleton
{

   
class Example

   
{

    
static void Main()

   
{

     
Singleton s1 = Singleton.Instance();

     
Singleton s2 = Singleton.Instance();

     
if (s1 == s2)

     
{

       
Console.WriteLine("Objects are of same instance");

     
}

     
Console.ReadKey();

   
}

 
}

 
class Singleton

 
{

   
private static Singleton _instance;

   
protected Singleton()

   
{    }

   
public static Singleton Instance()

   
{

     
if (_instance == null)

     
{

       
_instance = new Singleton();

     
}

     
return _instance;

   
}

 
}
}