Jean Paul's Blog

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

    Advertisements
  • 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
  • Advertisements

Archive for the ‘Design Patterns’ Category

eBook on Design Patterns

Posted by Paul on January 27, 2012

I am very much happy to compile my second eBook: Design Patterns in C#. It was a dedicated learning effort of past 1 year and I very much enjoyed the patterns. I believe Design Patterns will give good designing edges to the developers and enhance their Object Oriented skills.

Download eBook
You can download the eBook from Amazon here. (Formatted for Kindle, you can read it on your computer without Kindle Device)

Download Source Code (Visual Studio 2010)
You can download the source code for the examples here

Download Source Code (Visual Studio 2012)
You can download the source code for the examples here

Feedback
Please feel free to provide me comments or suggestions on improvements about this ebook.

Advertisements

Posted in C#, Design Patterns | Tagged: | 30 Comments »

Design Patterns eBook

Posted by Paul on January 27, 2012

I am very much happy to compile my second eBook: Design Patterns in C#. It was a dedicated learning effort of past 1 year and I very much enjoyed the patterns. I believe Design Patterns will give good designing edges to the developers and enhance their Object Oriented skills.

Download eBook
You can purchase & download the eBook from Amazon here. (Formatted for Kindle)

Download Source Code (Visual Studio 2010)
You can download the source code for the examples here

Download Source Code (Visual Studio 2012)
You can download the source code for the examples here

Feedback
Please feel free to provide me comments or suggestions on improvements about this ebook.

Posted in C#, Design Patterns | Tagged: | 30 Comments »

Facade Pattern

Posted by Paul on December 22, 2011

In this article I would like to explore the Façade design pattern. The actual pronunciation is fu’saad. The dictionary meaning of the word Façade is “A showy misrepresentation intended to conceal something unpleasant”

Now let us enter the challenge..

Challenge

You are working on a database application. Frequently you need to execute UPDATE and DELETE SQL queries. Each time there is a need to create the SqlConnection and SqlCommand class, assign the connection to command and execute the query.

The series of activities looks like:

SqlConnection connection = new SqlConnection(“connection string” );

SqlCommand command = new SqlCommand();

command.Connection = connection;

command.CommandText = “UPDATE Customer SET Processed=1”;

command.ExecuteNonQuery();

You need to repeat the same code wherever execute queries are required. How to make this code better?

Definition

“Provide a unified interface to a set of interfaces in a system. Facade defines a higher-level interface that makes the subsystem easier to use.”

Implementation

Using Façade, we can improve the situation. We can find only the query is different in each case – the parameters like connection string is common for the entire application.

SQLFacade.ExecuteSQL(“UPDATE query here..”);

After using the Façade the code will look like above.

The complicated code is being pulled to the background SQLFacade class.

namespace FacadePattern

{

public class SQLFacade

{

public static bool ExecuteSQL(string sql)

{

SqlConnection connection = new SqlConnection(“connection string”);

SqlCommand command = new SqlCommand();

command.Connection = connection;

command.CommandText = sql;

command.ExecuteNonQuery();

return true;

}

}

}

Façade pattern makes code better as depicted in the image below:

clip_image002

Summary

In this article we have seen how to use the Façade pattern to improve our code. It is similar to the use of reusable functions and it pulls out the complications and provides an easier interface for use. The associated code contains the classes we have discussed.

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

State Pattern

Posted by Paul on December 21, 2011

In this article I am going to explain the State Pattern. It is one among the 23 design patters and provides a good solution to a common problem. As usual the pattern starts with a challenge and then implementing the solution using the pattern.

Challenge

You are working on a job processing application. The application can handle only 1 job at a time. So when a new job arrives the system response will be weird. How to provide a better approach to the above problem?

Definition

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.”

Implementation

An enumeration named JobState is used to define the states used in our application.

public enum JobState

{

Ready,

Busy

}

This enumeration is used inside our Job class.

public class Job

{

private JobState _State;

public JobState State

{

get { return _State; }

set

{

_State = value;

if (OnJobStateChanged != null)

OnJobStateChanged(this, _State);

}

}

public bool AddJob(object jobParameter)

{

switch (State)

{

case JobState.Ready:

{

DoJob();

return true;

}

case JobState.Busy:

{

return false;

}

}

return false;

}

}

In the AddJob() method we can see the new job is taken only if the JobState is in Ready state. Here true will be returned by the method. If there is another job running, then the new job will not be queued and false will be returned.

Thus the object Job changes the behavior based on the internal state.

Application

The associated application contains the classes we discussed.

On executing the windows application and clicking the Assign Job button, you can see the following screen:

clip_image002

While a job is in process, we cannot add another job. If a try is made the response is:

clip_image004

Summary

In this article we have seen about State Pattern. The attachment file contains the source code of the application we have discuseed.

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

Flyweight Pattern

Posted by Paul on December 6, 2011

In this article we are discussing about Flyweight Design Pattern. It is one among the 23 design patterns and provides an improved way of managing objects.

Challenge

You are working on an Id Card Creation web application. The application has 1 lakh Student records for which Id Cards to be created.

Following is the StudentCard class that performs the id card generation. We need to call the GenerateIdCard() method to get the Id Card image after assigning the student Name, Address, Photo properties. Each card image generated is saved to file system.

clip_image002

The problem is the 1 Lakh class instances created. How to reduce the number of instances?

Definition

“Use sharing to support large numbers of fine-grained objects efficiently.”

Implementation

Using Flyweight pattern we can solve the above problem. We can see from the above problem that at a time only one instance is needed.

We can use only one instance of StudentCard class and share it inside the loop to assign the properties and generate id card.

The pattern is advisable on:

  • To reduce the number of instances
  • Sharing properties which are common

This was the old process:

clip_image004

Here depending on the Student count, instances of StudentCard are created.

This will be the new process:

clip_image006

Here only 1 instance of StudentCard is created.

Code View

Following is the code implementing Flyweight pattern:

StudentCard card = new StudentCard();

card.CollegeName = “College of Advanced Sciences”; // CommonProp

for (int i = 1; i <= 100; i++)

{

card.Name = names[random.Next(0, names.Length – 1)];

card.Address = addresses[random.Next(0, addresses.Length – 1)];

card.Photo = photos[random.Next(0, photos.Length – 1)];

list.Add(new System.Web.UI.WebControls.Image()

{

ImageUrl = card.GenerateIdCard()

});

}

Screen Shot

On running the attached web application you can see the following output. The data like Name, Address and Photo are randomly generated.

clip_image008

Drawbacks

Although the Flyweight pattern solves many problems, I would like to list some of the possible drawbacks of using it.

– More configuration code is needed to switch between properties

– Reduces performance in a multi-threaded environment if locks are used

Summary

In this article we have explored Flyweight design pattern. The pattern helps us in reducing system resources if correctly used. The associated source code contains the example we have discussed. Please let me know your comments on the article.

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

Factory Method Pattern

Posted by Paul 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.

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

Abstract Factory Pattern

Posted by Paul 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 Paul 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 »

Adapter Pattern

Posted by Paul on November 25, 2011

Most of you might have heard about Adapter Pattern. It is a pattern commonly used in our applications but without knowing it. Adapter Pattern is one among the 23 Design Patterns. In this article I would like to examine this pattern using a simple example.

Challenge

You are working on a Square class. You need to find the Area of it using Calculator class. But the Calculator class only takes Rectangle class as input. How to solve this scenario?

clip_image002

Definition

“Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.”

Implementation

Following are the class definitions for Rectangle and Calculator.

public class Rectangle

{

public int Width;

public int Height;

}

public class Calculator

{

public int GetArea(Rectangle rectangle)

{

int area = rectangle.Width * rectangle.Height;

return area;

}

}

As we cn see from the above example an instance of Rectangle is needed to calculate the area. If we have a square class of definition below, the calculation cannot be done.

public class Square

{

public int Size;

}

Here we have to create a new CalculatorAdapter to get the work done.

public class CalculatorAdapter

{

public int GetArea(Square square)

{

Calculator calculator = new Calculator();

Rectangle rectangle = new Rectangle();

rectangle.Width = rectangle.Height = square.Size;

int area = calculator.GetArea(rectangle);

return area;

}

}

The CalculatorAdapter performs the following functions:

· Takes the Square parameter

· Convert Square to Rectangle

· Call the original Calculator.GetArea() method

· Return the value received

The invoking code is shown below:

// Create Square class and assign Size from UI

Square square = new Square();

square.Size = SquarePanel.Width;

// Use Adapter to calculate the area

CalculatorAdapter adapter = new CalculatorAdapter();

int area = adapter.GetArea(square);

// Display the result back to UI

ResultLabel.Text = “Area: ” + area.ToString();

On running the sample application we can see the following results.

clip_image004

Note: We can have other examples including Interfaces to show the above pattern. For simplicity I have avoided the interfaces. In real life the AC to DC adapter is an example of the Adapter pattern as it makes the incompatible device and power supply work together.

Summary

In this article we have explored Adapter pattern. This pattern is useful in scenarios where incompatible types are dealt with. The associated source code contains the example application we have discussed.

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

LINQ2XML Example

Posted by Paul on November 21, 2011

This is one of the code sample which I worked over a forum.

From the xml file given below, we need to select the nodes with category attribute of value pending.

 

<root>
  <fault category=”pending”>
    <text>Pending Fault found on</text>
  </fault>
  <fault category=”repaired”>
    <text>Repaired Fault on</text>
  </fault>
  <genere>
    <text1>Aircraft</text1>
    <text2>Component</text2>
    <text3>Subsystem</text3>
  </genere>
</root>

 

Following the LINQ2XML Code to attain the same:

 

XElement xElement = XElement.Load(@”c:\\temp\\xml.txt”);
            var list = (from e in xElement.Elements(“fault”) where e.Attribute(“category”).Value == “pending”
                 select e).ToList();

            foreach (XElement xe in list)
                Console.WriteLine(xe.Value);

            Console.ReadKey(false);

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