Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Posts Tagged ‘design patterns’

Factory Method Pattern

Posted by JP on December 1, 2011

In the previous article you might have read about Abstract Factory. It says about abstracting a class with related objects. In this article we are discussing on Factory Method pattern. I am using the same ADO.NET Provider Factory class as example.

Let us see the challenge and evolve to the solution.

Challenge

You are working on a windows application. The application has 2 types of users based on the database license they have: Sql Server or Oracle.

So for each database operation you need to create the right database classes based on an enumeration DatabaseType.

public void InsertRecord()

{

if (AppContext.DatabaseType == DatabaseType.SqlServer)

{

SqlConnection connection = new SqlConnection();

SqlCommand command = new SqlCommand();

command.Connection = connection;

command.ExecuteNonQuery();

}

else if (AppContext.DatabaseType == DatabaseType.Oracle)

{

OracleConnection connection = new OracleConnection();

OracleCommand command = new OracleCommand();

command.Connection = connection;

command.ExecuteNonQuery();

}

}

The above code seems to be complex and needs repeating for each database operation spread throughout the application.

How to stop the repeating code and make things better?

Definition

“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.”

Implementation

The above problem can be resolved using Factory Method pattern. Here we provide an abstract class for defining the structure and associating all related objects (using Abstract Factory). Then the sub classes will be created deriving from this abstract class. The sub classes decide which classes to be instantiated.

The advantage is more quality and less code. Here we have to define an abstract class named DbProviderFactory. (already ADO.NET contains it)

public abstract class DbProviderFactory

{

public virtual DbCommand CreateCommand();

public virtual DbCommandBuilder CreateCommandBuilder();

public virtual DbConnection CreateConnection();

public virtual DbDataAdapter CreateDataAdapter();

public virtual DbParameter CreateParameter();

}

Then from the above abstract class we can derive concrete classes.

public class SqlClientFactory : DbProviderFactory

{

public override DbConnection CreateConnection()

{

return new SqlConnection();

}

public override DbCommand CreateCommand()

{

return new SqlCommand();

}

}

You can see from the above code SqlConnection() and SqlCommand() objects are created and supplied for DbConnection and DbCommand types respctively. Here DbConnection and DbCommand are other abstract classes.

Similary the Oracle implementation follows:

public class OracleClientFactory : DbProviderFactory

{

public override DbConnection CreateConnection()

{

return new OracleConnection();

}

public override DbCommand CreateCommand()

{

return new OracleCommand();

}

}

Replacing the Original Code

Now we are ready to replace our Insert() method code with the Factory Method classes. Here we are using an AppInit() code to create the factory which will be used throughout the application.

public void AppInit()

{

if (AppContext.DatabaseType == DatabaseType.SqlServer)

AppContext.DbProviderFactory = SqlClientFactory.Instance;

else if (AppContext.DatabaseType == DatabaseType.Oracle)

AppContext.DbProviderFactory = OracleClientFactory.Instance;

}

// NewInsertRecord method

private void NewInsertRecord()

{

DbConnection connection = AppContext.DbProviderFactory.CreateConnection();

DbCommand command = AppContext.DbProviderFactory.CreateCommand();

command.Connection = connection;

command.ExecuteNonQuery();

}

From the above code you can see that using Factory Method the code is reduced considerably but at a cost of new classes. The pattern provides much flexibility on adding a new database. (if another customer with PostgreSQL arrives J)

Abstract and Concrete Derivation

The following image depicts the relation between the abstract and concrete classes we have discussed.

clip_image002

Note

ADO.NET already includes the DbProviderFactory abstract class and concrete classes like SqlClientFactory, OleDbFactory etc. Additionally, using an ORM like Entity Framework automatically takes care of the database switching. The scenario mentioned here is for learning purposes.

Summary

In this method we have seen the Factory Method pattern. The example we discussed is included with the attachment.

Advertisements

Posted in Design Patterns | Tagged: , , | Leave a Comment »

Abstract Factory Pattern

Posted by JP on December 1, 2011

In this article I would like to explain the Abstract Factory pattern. This pattern is essential for learning the Factory Method and Bridge patterns.

Challenge

You are working on an ORM (Object Relational Mapping) framework creation. The framework could be used in different databases like:

  • Sql Server
  • Oracle
  • MS Access
  • OleDb

Based on the database type, you need to create related classes like:

  • SqlConnection, SqlCommand when Sql server
  • OracleConnection, OracleCommand when Oracle etc.

How to create a family of related objects without implementation of them?

Definition

“Provide an interface for creating families of related or dependent objects without specifying their concrete classes.”

Implementation

Our idea is to create an interface which contains all related objects like:

public abstract class DbProviderFactory

{

public abstract DbConnection CreateConnection();

public abstract DbCommand CreateCommand();

}

Luckily, ADO.NET already includes the same interface as Abstract Factory. The The definition is given below: (I have excluded some irrelevant methods from it)

namespace System.Data.Common

{

public abstract class DbProviderFactory

{

public virtual DbCommand CreateCommand();

public virtual DbCommandBuilder CreateCommandBuilder();

public virtual DbConnection CreateConnection();

public virtual DbDataAdapter CreateDataAdapter();

public virtual DbParameter CreateParameter();

}

}

From the above code we can see that the related classes are includes as a family without going to the implementation details.

The abstract class DbProviderFactory contains related classes which are abstract: DbCommand, DbConnection etc.

Concrete Implementations

ADO.NET provides the following implementations of the above abstract class DbProviderFactory.

· System.Data.SqlClient.SqlClientFactory

· System.Data.OleDb.OleDbFactory

The above classes implements all abstract methods from the base class. Thus it will be providing concrete implementations of DbConnection which is SqlConnection, DbCommand which is SqlCommand etc.

Instantiating from the above classes, we can start using the concrete implementations like following code.

SqlClientFactory factory = SqlClientFactory.Instance;

DbConnection connection = factory.CreateConnection();

DbCommand command = factory.CreateCommand();

command.Connection = connection;

command.CommandText = “query here”;

command.ExecuteNonQuery();

clip_image002

Summary

In this article we have seen the usage of Abstract Factory pattern through inbuilt ADO.NET DbProviderFactory class. In the next article of Factory Method pattern the above discussed code will be used. So I am not attaching any source code with this article.

Posted in Design Patterns | Tagged: , , | Leave a Comment »

Chain of Responsibility Pattern

Posted by JP on November 27, 2011

Chain of Responsibility is one among the 23 Design Patterns by Gang of Four. It is an interesting pattern and similar to Observer pattern. In this article we are exploring the Chain of Responsibility pattern.

I am using the same Challenge and Solution style for explaining this pattern.

Challenge

You are working on an application in which the Logic class generates various messages. The messages are of two types.

  • Normal Priority
  • High Priority

The Normal Priority messages are to be processed by Logger class and High Priority messages by Emailer class.

You have to make the design in such a way that the Logic class need not think about right handler of the message. It will just send the message.

How the design will proceed?

Definition

“Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.”

Control Flow

clip_image002

Implementation

Following is the definition for Logic class:

public class Logic

{

public IReceiver Receiver;

public void CreateMessage(Message message)

{

if (Receiver != null)

Receiver.HandleMessage(message);

}

}

We can see from the above code that the Logic class has a property of type IReceiver. On the CreateMessage method this Receiver is used to handle the message. So only one receiver is registered by the Logic class instance.

Following are the definition of Message class and MessagePriority enumeration:

public class Message

{

public string Text;

public MessagePriority Priority;

}

public enum MessagePriority

{

Normal,

High

}

Following are the Receiver Interface and Implementation classes:

public interface IReceiver

{

bool HandleMessage(Message message);

}

public class Logger : IReceiver

{

private IReceiver _nextReceiver;

public Logger(IReceiver nextReceiver)

{

_nextReceiver = nextReceiver;

}

public bool HandleMessage(Message message)

{

if (message.Priority == MessagePriority.Normal)

{

Trace.WriteLine(message.Text + ” : Logger processed it!”);

return true;

}

else

{

if (_nextReceiver != null)

_nextReceiver.HandleMessage(message);

}

return false;

}

}

public class Emailer : IReceiver

{

private IReceiver _nextReceiver;

public Emailer(IReceiver nextReceiver)

{

_nextReceiver = nextReceiver;

}

public bool HandleMessage(Message message)

{

if (message.Priority == MessagePriority.High)

{

Trace.WriteLine(message.Text + ” : Emailer processed it!”);

return true;

}

else

{

if (_nextReceiver != null)

_nextReceiver.HandleMessage(message);

}

return false;

}

}

From the above code we can see that each receiver class checks the message priority and processes it. If the priority is not matching it is send to the next receiver in the chain.

Here each receiver takes care of passing the unprocessed message. The next receiver is stored through the constructor of each receiver.

The chain will be executed until:

  • Message is processed
  • Receiver chain exhausted

Code Execution

The windows forms application attached can be used to test the control flow.

clip_image004

Here the chain is built as following:

  • Logic class holds first receiver which is Logger
  • Logger class holds the next receiver which is Emailer
  • Emailer class have null receiver denoting end of chain

Following code depicts the above chain creation:

Logic logic = new Logic();

logic.Receiver = new Logger(new Emailer(null));

Note: Please note that the advantage of this pattern is decoupling of sender and receiver. The sender does not think about the right receiver. Instead it will pass the request and the appropriate receiver should process it. The above example can be written using a list of receivers in the Logic class with a Boolean property mentioning whether the message is processed or not.

Comparing Observer and Chain of Responsibility

In the case of Observer pattern all the registered receivers will get the request. Each of the receivers is interested in processing it. But in chain of responsibility the request is passed until it is not processed.

clip_image006

Summary

In this article we have explored Chain of Responsibility pattern with a C# example. The associated source code contains the example we discussed.

Posted in Design Patterns | Tagged: , , | Leave a Comment »

My Favorite Design Patterns

Posted by JP on November 26, 2010

Pattern Definition Type
Singleton

Ensure a class only has one instance, and provide a global point of access to it.

 
Command

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

 
Template Method

Define the skeleton of an algorithm in an operation, deferring some
steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

 
Factory Method

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.

 
Builder

Separate the construction of a complex object from its representation so that the same construction processes can create different representations.

 
Decorator

Attach additional responsibilities to an object dynamically. Decorators
provide a flexible alternative to sub classing for extending functionality.

 

Posted in C# | Tagged: | Leave a Comment »