Friday, June 3, 2011

Singleton Design Pattern in .Net (C#)

Singleton Design Pattern
This pattern ensures that only a single instance of a given object can exist. It prevent developers from creating multiple instances of class. It is very simple patter to implement it in our applications. Go through the following example, it will give you the exact idea behind the Singleton Design Pattern.

    //sealed class cannot be inherited.
//thus we can prevent creating objects
//through its subclasses.
public sealed class MyDataContext
{
private static readonly MyDataContext _context = new MyDataContext();

//by defining a private constructor
//we cannot create an object from outside the class.
private MyDataContext()
{
}

public static MyDataContext Create()
{
return _context;
}


//Other operations.
}


Here in this example we can create an instance of MyDataContext class only by calling the Create method. We have ensure singleton by



  • declaring class as sealed

  • defining a private constructor to prevent outside object initialization

Hope all of you are now clear with Singleton Design Pattern. In my opinion this pattern is most used in Desktop Applications. It is possible to implement this in Asp.Net, I will post an article on that soon.

Factory Method Design Pattern in .Net (C#)

Factory Method Pattern
Like Abstract Factory Pattern, Factory Method Pattern is also a part of Creational patterns. This pattern is also to create concrete product objects. There are many ways are available to implement Factory Method Pattern in .Net. Here I will demostrate a typical structure of Factory Method Pattern.
Factory Method Pattern Structure


  1. Creator: An interface to create product objects. which contains either factor method declarations or factory methods itself. (In .Net an Abstract class or Interface is used to create Creator).

  2. Concrete Creator: It implements the factory methods declared within the Creator. (It will be class declaration)

  3. Product: Declares an interface to define products. (It will be either an Abstract class or an Interface)

  4. Concrete Product: It implements the Product to define a concrete object. (it will be class).

Have a look on the following example. Here in this example I have created all the above mentioned items.


1. Creating Product. In the example I have used an Interface named "IFruit" to create a Product.


Note: Here in our example I have used Interface instead of base classe, you can use abstract classes because abstract classes offer versioning benefits over pure interfaces.


    public interface IFruit
{
string GetDescription();
}

2. Creating concrete products. In our example I have created two concrete products named "Apple" and "Orange".

    public class Apple : IFruit
{
public string GetDescription()
{
return "I'm an Apple....!";
}
}

public class Orange : IFruit
{
public string GetDescription()
{
return "I'm an Orange....!";
}
}



3. Creating Creator: In our example I have created a creator named "IFruitFactory".

    public interface IFruitFactory
{
IFruit CreateApple();
IFruit CreateOrange();
}
4. Creating Concrete Creator: We have a concrete creator named "FruitFactory" is in our example.
    public class FruitFactory : IFruitFactory
{
public IFruit CreateApple()
{
return new Apple();
}

public IFruit CreateOrange()
{
return new Orange();
}
}
Next we can consume our sample application
            IFruitFactory fruitFactory = new FruitFactory();
IFruit fruit;

fruit = fruitFactory.CreateApple();
Console.WriteLine(fruit.GetDescription());

fruit = fruitFactory.CreateOrange();
Console.WriteLine(fruit.GetDescription());



Hope all of you are clear with Factory Method pattern. Above I mentioned only the typical way of defining Factory Method Pattern; there are several other ways to implement the same. Try it yourself. :-)

Monday, May 30, 2011

Abstract Factory Pattern in .Net with Example (C#)

Abstract Factory Pattern
Abstract Factory pattern is used to create concrete class instances without specifying the exact class type (ie, to create instance of a classe without specifying the exact class type). Abstract Factory Pattern is one of the Creational Design Patterns. Creational Design patterns are design patterns that handle object creation mechanisms.

The Abstract Factory Pattern Structure




  1. Abstract Factory: Declares an interface that creates abstract objects.


  2. Concrete Factory: Which implements the operations declared in the Abstract Factory. In Abstract Factory pattern, it may have multiple Concrete Factory classes.


  3. Abstract Product: Declares an interface that creates abstract result objects.


  4. Concrete Product: This will be the object created by the corresponding concrete factory. It implements the opreations declared in the Abstract Product.


  5. Client: Client will use only interfaces as part of Abstract Factory and Abstract Product.
For more clarification and step by step implementation of Abstract Factory Pattern, please go through the following example. The following application act as an interface for both Sql Server and Oracle databases. See how it is implemented.

Note: The following example does not cover the whole database functionality. It is just created to explain Abstract Factory pattern. Even though you can modify the code to accomplish the whole database functionality.
A Real world Example for Abstract Factory Pattern



Class Diagram


1. First we will create an Abstract Product. The below code shows an interface ("IDatabaseHelper") which will act as an Abstract Product in our sample application.

    public interface IDatabaseFactory
{
IDatabaseHelper CreateHelper();
}


Note: You can use either Inerface or an Abstract Class to create an Abstract Product.



2. Next we will create two Concrete Product which implements the Abstract Product. The classes "OracleDatabaseHelper" and "SqlDatabaseHelper" will be our Concrete Products in our sample application.

  public class SqlDatabaseHelper : IDatabaseHelper
{
private System.Data.SqlClient.SqlConnection _connection;

public System.Data.IDataReader ExecuteReader()
{
//todo
return null;
}

public System.Data.DataSet ExecuteDataSet()
{
//todo
return null;
}

public int ExecuteNonQuery()
{
//todo
return 0;
}

public object ExecuteScalar()
{
//todo
return null;
}

public void OpenConnection()
{
_connection = new System.Data.SqlClient.SqlConnection();

//todo
}

public void CloseConnection()
{
_connection.Close();
//todo
}

}



public class OracleDatabaseHelper : IDatabaseHelper
{

System.Data.OleDb.OleDbConnection _connection;

public System.Data.IDataReader ExecuteReader()
{
//todo
return null;
}

public System.Data.DataSet ExecuteDataSet()
{
//todo
return null;
}

public int ExecuteNonQuery()
{
//todo
return 0;
}

public object ExecuteScalar()
{
//todo
return null;
}

public void OpenConnection()
{
_connection = new System.Data.OleDb.OleDbConnection();

//todo
}

public void CloseConnection()
{
_connection.Close();
//todo
}
}
3. Next we will create an Abstract Factory. Here "IDatabaseFactory" interface will be our Abstract Factory.
    public interface IDatabaseFactory
{
IDatabaseHelper CreateHelper();
}
4. Next we will create a Concrete Factory which implements the Abstract Factory. Here "OracleDatabaseFactory" and "SqlDatabaseFactory" classes will act as Concrete Factory through our sample application.

Note: In Abstract Factory pattern, it is possible to have multiple Concrete Factory Classes which all implements the Abstract Factory.
 public class SqlDatabaseFactory : IDatabaseFactory
{
public IDatabaseHelper CreateHelper()
{
return new SqlDatabaseHelper();
}
}


public class OracleDatabaseFactory : IDatabaseFactory
{
public IDatabaseHelper CreateHelper()
{
return new OracleDatabaseHelper();
}
}
5. Next we can create a Client, which will use the Abstract Factory and Abstract Product. Here in our example class "DatabaseClient" acts as a client.

    public class DatabaseClient
{
private IDatabaseHelper _helper;

public DatabaseClient(IDatabaseFactory factory)
{
_helper = factory.CreateHelper();
//do any other code if needed.
}

public IDatabaseHelper Helper
{
get
{
return _helper;
}
}
}
To use the above pattern you can follow the following sample.
            DatabaseClient dbClient = new DatabaseClient(new SqlDatabaseFactory());
dbClient.Helper.OpenConnection();
//do other operations
dbClient.Helper.ExecuteNonQuery();
//do other operations
dbClient.Helper.CloseConnection();
I will upload the sample application later. You can try this example. Feel free to ask questions and doubts.