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 pattern’

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 »

Template Method Pattern

Posted by JP on November 15, 2011

Template Method is a widely used design pattern and it provides great flexibility in our designs. This is one of my favourite patterns.

Challenge

You are creating machines for creating Pizza and Burger. When we look closely we can see all the machines have some operations in common and in the same order.

  • Start
  • Produce
  • Stop

The Start operation consists of turning on the machines, do the system check for any troubles and turning on the indicators.

The Produce operation does the respective production of item.

The Stop operation shutdowns the internal workings of the machine, turns off the indicators and power offs the machine.

The challenge is to create more machines like Cheese Burger, Pan Pizza with less custom implementations. We need to take care that the duplicate codes are avoided in our design.

Definition

“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.”

Implementation

We can see that all the operation appears in the same sequence. Often the Start and Stop operation are common to both Pizza and Burger machines.

So we can define a skeleton of algorithm (or the order of invocation) like below:

Start

Produce

Stop

We can see all the machines have this order of execution. Only the Produce operation will be different.

So creating an Execute() method to incorporate this would look like:

public class Machine

{

public void Execute()

{

Start();

Produce();

Stop();

}

}

By calling the Execute() method we can invoke all the 3 methods in the right order. Keeping the Execute() method in the base class as public, we can create Produce() method as virtual so that it can be overridden. For more customization we are making all the 3 methods as virtual.

Note

For virtual methods, a default implementation will be provided in the base class. The derived class may/may not override it.

For abstract methods, we need to override them in the derived class. There won’t be any default implementation in the base class.

The modified Machine class will look like below:

public class Machine

{

public void Execute()

{

Start();

Produce();

Stop();

}

protected virtual void Start()

{

Trace.WriteLine(“Machine.Starting..”);

}

protected virtual void Produce()

{

Trace.WriteLine(“Machine.Producing..”);

}

protected virtual void Stop()

{

Trace.WriteLine(“Machine.Stopping..”);

}

}

Please note the class uses virtual keyword so that the derived classes can override.

The derived class PizzaMachine will look like:

public class PizzaMachine : Machine

{

protected override void Produce()

{

Trace.WriteLine(“PizzaMachine.Producing..”);

}

}

The derived class BurgerMachine will look like:

public class BurgerMachine : Machine

{

protected override void Produce()

{

Trace.WriteLine(“BurgerMachine.Producing..”);

}

}

Please note that both of them derives from Machine class and use the keyword override to custom implement the Produce() method.

Execution

Now we can execute the PizzaMachine using the Execute() method of base class.

new PizzaMachine().Execute();

Let us examine how the order of execution works.

  1. Machine.Execute() is invoked
  2. Machine.Start() is invoked
  3. PizzaMachine.Produce() is invoked
  4. Machine.Stop() is invoked

Please note the step 3 above, in which the execution shifts from Machine class to PizzaMachine class. This is the power of Template Method pattern. Here the order of execution is maintained and a custom production is done.

Note

The underlying detail of how the above code works goes to Virtual Method Table (VMT) where the base class method address is kept in a table. The derived classes will be having a new address for the derived method. This will be replacing the original base class method address.

The control flow is depicted in the image below.

clip_image002

Test Application

A test application is created with a GUI using WinForms.

clip_image004

Summary

In this article we have seen the advantage of Template Method design pattern and the problem it tries to address. The source code contains the classes and application explained.

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

Observer Design Pattern in C#

Posted by JP on November 13, 2011

Definition
The Gang of Four book (Design Patterns: Elements of Reusable Object-Oriented Software, 1995) says that the Observer design pattern should “Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.”

Purpose of Observer Pattern
The Observer pattern is to notify the interested observers about some change occurred. We can add more observers in runtime as well as remove them.
Example: We have a form to select the color. For each color change we need to update the entire application. There will be observers listening to the color change event for updating themselves.

Subject and Observers
The two important key terms in the pattern are Subject and Observer.
Subject is the object which holds the value and takes responsibility in notifying the observers when the value is changed. The subject could be a database change, property change or so.
We can conclude that the subject contains the following method implementations.
public interface ISubject
{
void Register(IObserver observer);
void Unregister(IObserver observer);

void Notify();
}
The Observer is the object listening to the subject’s change. Basically it will be having its own updating/calculating routine that runs when get notified.
public interface IObserver
{
void ColorChanged(Color newColor);
}
In the above example, we are using an observer interface which has a ColorChanged method. So the interested observers should implement this interface to get notified.
There will be only one Subject and multiple number of Observers.

Registering and Unregistering
In the above interface, the observer can use the Register() method to get notified about changes . Anytime, it can unregister about notifications using the Unregister() method.

Notifying
The Notify() method will take care of calling the listening observers.

Associations
The Subject and Observer objects will be having a one-to-many association.
ObserverPatt1.gif

Using the Code
The associated code is having a main form, where the Subject would be a class named ColorSubject.
public class ColorSubject : ISubject
{
private Color _Color = Color.Blue;

public Color Color
    {
get { return _Color; }
set
        {
            _Color = value;
            Notify();
        }
    }

    #region ISubject Members

private HashSet<IObserver> _observers = new HashSet<IObserver>();

public void Register(IObserver observer)
    {
        _observers.Add(observer);
    }

public void Unregister(IObserver observer)
    {
        _observers.Remove(observer);
    }

public void Notify()
    {
        _observers.ToList().ForEach(o => o.ColorChanged(Color));
    }
    #endregion
}
The class implements ISubject interface and thus takes care of registering, unregistering and notifying the interested observers. All the observers keep registered with the ColorSubject object.

Screen Shot of Application
ObserverPatt2.gif
On running the associated project, we can see a color selector form, which acts as as the subject. All the other forms are observers listening to the ColorChanged event.

Note: The multicast event model in .Net can also be considered as an observer pattern. Here the interested parties register a method with the subject (might be a button) and whenever the button is clicked (an event) it invokes the registered observers (subscribers)

Conclusion
In this article we have seen what Observer pattern is and an example implementation.  The associated source code can be found here.

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

Builder Pattern – A Robot Example

Posted by JP on November 13, 2011

In this article I am trying to demonstrate the usage of Builder Pattern using a Computer Assembling Robot. Builder Pattern is one among the 23 patterns by Gang Of Four.  

Definition of Builder

The GoF says that the Builder design patterns let you “Separate the construction of a complex object from its representation so that the same construction processes can create different representations.”

Problem to Solve

In a computer manufacturing unit, depending on the configuration – they have to create computers.  The challenge is that the computer parts are chosen in the runtime.  The order can contain n number of computers based on the same configuration.  This could be the right example to implement the Builder pattern where each robot will be setup with a particular computer configuration.  The robot will continue creating the same configuration based computer n times.

Computer Peripherals

Processor:   Intel / AMD

Monitor: Samsung / LG

Speakers: None / Stereo / Surround

Execution

The Windows Form UI allows the user to choose the configuration.  The virtual factory provides up to 3 robots to be added before the actual assembling takes place.

1.gif

Code Explained

Following is the screen shot of the main class named Robot.  The class contains a property called Peripherals which can be used to configure the peripherals added: like CPU as Intel, Monitor as Samsung etc.

After adding the peripherals, we can call the Create() method.  It will iterate through the Peripherals dictionary and calls the appropriate methods to integrate the peripherals.  This allows us to choose the peripherals at run time as well as the sequence too.  

If the Peripheral dictionary contains CPU then the AssembleCPU() method is invoked.

If the Peripheral dictionary contains Monitor then the AssembleMonitor () method is invoked.

2.gif

The class Peripheral is an enumeration as following:

public enum Peripheral

{

Processor,

Monitor,

Speakers

}

The associated source code can be found here.

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

Dynamically extending responsibilities using Decorator Pattern

Posted by JP on December 9, 2010

Definition

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

Closed for Modification and Open for Extension

One of the main challenges we face in development is Change. The Closed for Modification and Open for Extension principle says a new functionality can be added by keeping the original code unchanged.

Example:

You have an Album class today which is just blank now. Tomorrow if the customer wants a Christmas tree on that.. What would be our approach?

We will modify the original Album class to incorporate the Christmas tree on it. This should not be the best approach. There is a better approach to this. We can still keep the Album class unchanged and add the Christmas tree to it. Everything happens in the runtime… that is the cool part of it.

Some more examples

We can see real life controls like Form, Button etc. There would be a Form class which having inbuilt functionality. Still the user can use it and add new controls on it / extend the functionality. Here we will be basically deriving from the existing Form/Button class and add new methods or properties to it.

The difference between the above approach and Decorator pattern is that, in the Decorator pattern, we are assigning the responsibility in the runtime.

Conclusion on Change

So basically we can conclude that whenever changes are required, the possible solutions could be:

· Change the original class

· Subclass it and create instance of subclass

· Use Decorator Pattern and still using the original class instance

Here we are going to see how we can use Decorator Pattern to help with the following scenario.

Requirement

The requirement here would be to provide a default Album object and based on dynamic requirement from the user in runtime, we have to draw other pictures to the album.

clip_image002

Design

Our first class would be the Album class which has a Graphics object as parameter.

It contains a Draw() method which is virtual and just clears the graphics object.

public class Album

{

public Graphics Graphics

{

get;

set;

}

public Album()

{

}

public Album(Graphics graphics)

{

Graphics = graphics;

}

public virtual void Draw()

{

Graphics.Clear(Color.White);

}

}

Decorator

We are adding the class named AlbumDecorator which will serve as the base class for all decorators.

public abstract class AlbumDecorator : Album

{

protected Album _album;

public AlbumDecorator(Album album)

{

_album = album;

}

public override void Draw()

{

_album.Draw();

}

}

It takes an Album class as parameter in the constructor.

There are ChristmasTreeDecorator, SantaClausDecorator, StarDecorator deriving from AlbumDecorator:

public class ChristmasTreeDecorator : AlbumDecorator

public class SantaClausDecorator : AlbumDecorator

public class StarDecorator : AlbumDecorator

Each class deriving from AlbumDecorator would be having it’s own picture to draw.

Invoking

In the main form we create an instance of Album class and assigns it to form field _album.

private Album _album;

_album = new Album(_graphics);

_album.Draw();

In the runtime, when user wanted Christmas Tree, instance of ChristmasTreeDecorator is created.

_album = new ChristmasTreeDecorator(_album);

_album.Draw();

In the above code we can see the same _album.Draw() method is called.

How it works

Whenever we call the Draw() method of a decorator class, it in turns calls the original Album.Draw(). After that it will call it’s own Draw() method. In this way we can pass the same album instance to multiple decorators. If there are 10 decorators, all the decorator Draw() methods will be invoked.

You can test this placing a breakpoint inside the StarDecorator Draw() method.

Note

Using decorator we can add dynamic responsibilities to an object in runtime. This provides us the flexibility of creating instance of decorators on need base. This would provide real advantage in scenarios like the additional responsibility instance consists of much memory usage.

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

Command Pattern – Undo Example

Posted by JP on October 18, 2010

Friends, here I am trying to show the usage of Command Design Pattern, one among 23 design patterns.

Personally I like this pattern very much, it is making use of good object oriented constructs and simplifies the logic of enabling Undo. 

Scenario

You are working on a painting application.  For each brush stroke you need to provide the Undo feature.

The brushes presently available are square and rectangle. In future more and more brushes will be available.  Our challenge is to provide the user with Undo feature. Clearly, on clicking the undo button, the last stroke should be cleared from the canvas.

CommandPattern.png

Command Pattern applied to the scenario

The definition of Command Pattern says “Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations”

Command Pattern Explained

The pattern says that all the operations should be converted into objects, so that we log the objects.  In future we can call Do() or Undo() operations on the object.   The object should be smart enough to store the request parameters inside it to support the Do and Undo operations.

Command Pattern for our Scenario

Applied to our scenario, we have got two brushes:

  • Square Brush
  • Rectangle Brush

The other parameters would be Canvas which is the PictureBox control on which we draw and the X, Y location on mouse pointer on the canvas.   Formulating this we can create 2 classes:

SquareCommand class for square drawing operation and Rectangle class for rectangle drawing operation.

The Do() operation would be drawing a square for the square class and drawing a rectangle for the rectangle class.

We can formulate an interface called ICommand having the Do() and Undo() methods.

public interface ICommand

{

void Do();

void Undo();

}

The classes would be SquareCommand and RectangleCommand which implement s the above interface.

Architecture – Class Diagram

2.gif

Implementation

When the application is executed, the user will be having a blank white screen, with a set of colors to choose from.  The default brush selected will be Square and on clicking the canvas a new square will be drawn on the canvas.  The default color selected is Blue and is stored in the variable _activeColor.

The form level variables declared are:

private ShapeEnum _activeShape = ShapeEnum.Square;

private Color _activeColor = Color.Blue;

private Bitmap _bitmap;

private Graphics _graphics;

For each mouse down operation a new square class will be created.  That means if 10 clicks are made 10 square classes will be created and the Do() operation is called   An enumeration variable called _activeShape is used to keep track of the current shape selected by the user.  The mouse down event would look like the following.

private void Canvas_MouseDown(object sender, MouseEventArgs e)

{

// Each mouse down creates a new command class instance

ICommand command = null;

if (_activeShape == ShapeEnum.Square)

command = new SquareCommand(_bitmap, _activeColor, e.X, e.Y);

else if (_activeShape == ShapeEnum.Rectangle)

command = new RectangleCommand(_bitmap, _activeColor, e.X, e.Y);

command.Do();

_commandStack.Push(command);

RefreshUI();

}

Let us take an example: assume the user clicked the mouse at Point X=100 and Y=200.  As the _activeShape is Square,  a new SquareCommand class instance is created with arguments e.X and e.Y.  The remaining arguments are bitmap and the active color.  Then the command instance would be pushed to a stack and the Do() operation is called.

The stack provides a storage for usage of the command instance later.  The declaration of stack is:

private Stack<ICommand> _commandStack = new Stack<ICommand>();

Inside the SquareCommand Class

We can have a look on the Square class.  Both the SquareCommand and RectangleCommand class will be having same implementations except in the Do() operation of drawing the respective shape.

public class SquareCommand : ICommand

{

private Point _point;

private Bitmap _bitmap;

private Graphics _graphics;

private Color _color;

public SquareCommand(Bitmap bitmap, Color color, int x, int y)

{

_bitmap = bitmap;

_graphics = Graphics.FromImage(_bitmap);

_color = color;

_point = new Point(x, y);

}

public void Do()

{

// Save the current pixel colors for a future UNDO perform

SaveCurrentPixels();

// Do the drawing

_graphics.FillRectangle(new SolidBrush(_color),

new Rectangle(_point.X, _point.Y, Width, Height));

}

private const int Width = 50;

private const int Height = 50;

private IList<Color> _colors = new List<Color>();

private void SaveCurrentPixels()

{

for (int i = _point.X; i < _point.X + Width; i++)

for (int j = _point.Y; j < _point.Y + Height; j++)

_colors.Add(_bitmap.GetPixel(i, j));

}

/// <summary>

/// Perform Undo by restoring back the pixels to previous colors

/// </summary>

public void Undo()

{

int ix = 0;

for (int i = _point.X; i < _point.X + Width; i++)

for (int j = _point.Y; j < _point.Y + Height; j++)

_bitmap.SetPixel(i, j, _colors[ix++]);

}

}

The constructor is called with the bitmap and the x, y positions which are then stored into class fields.  When the Do() method is called the current pixel colors are saved into the _colors list.  This would enable us to perform the Undo() method later.  After that the graphics.FillRectangle() method is called to draw the square.  The width and height of the square would be set to 50 pixels using the constants Width and Height respectively.

The Undo() method just restores the previous pixel values using the bitmap.SetPixel method() by iterating through each pixel starting from x, y position.

Performing the Undo() on clicking Undo button

As we encapsulated each operation to a class with parameters and logged them into the command stack, it is now easier to call the Undo() method.  Please remind that on clicking the Undo button we have to get the last operation instance and call the Undo() method of it, and removing it from the stack.

The code for it is:

private void UndoButton_Click(object sender, EventArgs e)

{

// Check command stack contains items

if (_commandStack.Count > 0)

{

// Remove the last command

ICommand lastCommand = _commandStack.Pop();

// Call the Undo method

lastCommand.Undo();

}

RefreshUI();

}

First, the command stack count is checked to ensure there are commands inside it.  Then the last command is popped out using the Pop() method.  It will give us the last instance in the stack as well as removes it.  Then, the Undo() operation is invoked. After, the RefreshUI() method is called to update the UI with the changes.

Note

The command pattern provides an object oriented manner to provide Undo feature to our application in a flexible manner.

But the creation of lot of object instances is one of the draw back of this method which usually people say about.  I would say that in the other hand, the command pattern is giving us the advantage of keeping the code more manageable.

Source Code

I am happy to let you know that the source code for the article is available at c-sharpcorner.com

Link: http://www.c-sharpcorner.com/uploadfile/40e97e/3862/default.aspx

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

Builder Pattern through a Robot Example

Posted by JP on October 8, 2010

Builder Pattern

In this article I am trying to demonstrate the usage of Builder Patter using a Computer Assembling Robot.  Builder Pattern is one among the 23 patters by Gang Of Four. 

Definition of Builder

The GoF says that the Builder design patterns let you “Separate the construction of a complex object from its representation so that the same construction processes can create different representations.”

Problem to Solve

In a computer manufacturing unit, depending on the configuration – they have to create computers.  The challenge is that the computer parts are chosen in the runtime.  The order can contain n number of computers based on the same configuration.  This could be the right example to implement the Builder pattern where each robot will be setup with a particular computer configuration.  The robot will continue creating the same configuration based computer n times.

Computer Peripherals

Processor:   Intel / AMD

Monitor: Samsung / LG

Speakers: Yes / No

Execution

The Windows Form UI allows the user to choose the configuration.  The virtual factory provides upto 3 robots to be added before the actual assembling takes place.

clip_image002[4]

Code Explained

Following is the screen shot of the main class named Robot.  The class contains a property called Peripherals which can be used to configure the peripherals added: like CPU as Intel, Monitor as Samsung etc.

After adding the peripherals, we can call the Create() method.  It will iterate through the Peripherals dictionary and calls the appropriate methods to integrate the peripherals.  This allows us to choose the peripherals at run time as well as the sequence too. 

 

If the Peripheral dictionary contains CPU then the AssembleCPU() method is invoked.

If the Peripheral dictionary contains Monitor then the AssembleMonitor () method is invoked.

 

public partial class Robot : UserControl

    {

        /// <summary>

        /// Dictionary containing peripheral and the option

        /// </summary>

        public Dictionary<Peripheral, string> Peripherals = new Dictionary<Peripheral, string>();

 

        /// <summary>

        /// The core method used to create different representations

        /// </summary>

        public void Create()

        {

            while (true)

            {

                // Create new Computer

                _computer = new Bitmap(Images.Computer);

 

                foreach (Peripheral peripheral in Peripherals.Keys)

                {

                    if (peripheral == Peripheral.Processor)

                        AssembleCPU(Peripherals[peripheral]);

 

                    if (peripheral == Peripheral.Monitor)

                        AssembleMonitor(Peripherals[peripheral]);

 

                    if (peripheral == Peripheral.Speakers)

                        AssembleSpeakers(Peripherals[peripheral]);

 

                }

 

                AddToStore();

            }

        }

 

        public Robot()

        {

            InitializeComponent();

        }

 

        private Bitmap _computer;

 

        private PictureBox _pictureBox;

 

        private void AddToStore()

        {

            _pictureBox = new PictureBox();

            _pictureBox.BorderStyle = BorderStyle.FixedSingle;

            _pictureBox.Image = _computer;

            _pictureBox.Height = _computer.Height;

            _pictureBox.Width = _computer.Width;

 

            try

            {

                MyDelegate del = new MyDelegate(AddToParent);

                IAsyncResult result = Store.BeginInvoke(del);

                while (!result.IsCompleted)

                    Application.DoEvents();

            }

            catch

            {

                // As no stop button provided we have to abort the thread

                Thread.CurrentThread.Abort();

            }

        }

 

        private void AddToParent()

        {

            Store.Controls.Add(_pictureBox);

 

            if (Store.Controls.Count > 1)

            {

                Control lastControl = Store.Controls[Store.Controls.Count – 2];

                _pictureBox.Top = lastControl.Top + lastControl.Height + 1;

                Store.ScrollControlIntoView(_pictureBox);

            }

        }

 

        private delegate void MyDelegate();

 

        private const int Delay = 500;

 

        public void AssembleCPU(string model)

        {

            AddLog("Assembling CPU " + model + "..");

 

            Thread.Sleep(Delay);

            Application.DoEvents();

        }

 

        public void AssembleMonitor(string model)

        {

            AddLog("Assembling Monitor " + model + "..");

 

            Thread.Sleep(Delay);

            Application.DoEvents();

        }

 

        public void AssembleSpeakers(string model)

        {

            AddLog("Assembling Speakers " + model + "..");

 

            if (model == "Stereo")

                _computer = new Bitmap(Images.ComputerWith2Speaker);

            else

                _computer = new Bitmap(Images.ComputerWithSurroundSpeakers);

 

            Thread.Sleep(Delay);

            Application.DoEvents();

        }

 

        private void AddLog(string msg)

        {

            LogBox.Items.Add(msg);

 

            LogBox.SelectedIndex = LogBox.Items.Count – 1;

        }

    }

The class Peripheral is an enumeration as following:

    public enum Peripheral

    {

        Processor,

        Monitor,

        Speakers

    }

 You can find the entire article and source code in c-sharpcorner.com

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