Archive for the ‘Design Patterns’ Category

Strategy Pattern

Posted: December 1, 2010 in Design Patterns

The Strategy Pattern is a GOF (Gang of Four) behavioral pattern where the intent is to “define a family of algorithms, encapsulate each one, and make them interchangeable”.

This pattern gives the client the flexibility to solve the same problem using different algorithms. The client can switch to any algorithm.

In the code below, StrategyContext class accepts the SortType parameter which gives the client the flexibility to select the algorithm without knowing the internal implementation. Each algorithm is implemented as a separate class and its contract is defined by an interface. Any new algorithm to be introduced has to obey the contract defined by the interface.

————————————————————————————-
Source Code
————————————————————————————-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatterns
{
// Interface with alogorithm definition
public interface ISort
{
void Sort();
}

// Class encapsulating algorithm
public class BubbleSort : ISort
{

#region ISort Members

public void Sort()
{
Console.WriteLine(“Bubble Sort”);
}

#endregion
}

public class ShellSort : ISort
{

#region ISort Members

public void Sort()
{
Console.WriteLine(“Shell Sort”);
}

#endregion
}

// Context class for clients to interact and call appropriate
// strategy algorithm
public class StrategyContext
{
private ISort sortType;

public StrategyContext()
{
}

public StrategyContext(ISort _sortType)
{
sortType = _sortType;
}

public ISort SortType
{
get { return sortType; }
set { sortType = value; }
}

// Execute the algorithm
public void PerformAction()
{
if(sortType != null)
sortType.Sort();

else
{
throw new Exception(“Sort type not defined for the Context”);
}
}

}

public class Client
{
static void Main()
{

StrategyContext context = new StrategyContext(new BubbleSort());
context.PerformAction();

context = new StrategyContext();
ShellSort shellSort = new ShellSort();
context.SortType = shellSort;
context.PerformAction();

Console.ReadLine();
}
}
}

Advertisements

Factory and Abstract Factory patterns are creational patterns.

Factory pattern – “Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses.” This is a loosely coupled model as it returns an instance of one of several possible classes, depending on the data provided to it.The calling object can simply request the factory to return the object it needs, without actually knowing how to create that object i.e. through interface.In order to add or remove a new module, one only needs to modify the decision code in the factory.

Abstract factory – Provide an interface for creating families of related or dependent objects without specifying their concrete classes. This is one more level of abstraction above the factory pattern. Abstract factory is a factory object that returns one of the several factories.

Code snippet for both patterns is as seen below :

——————————————————————————————————————————————
Factory pattern sample

using System;

namespace DesignPatterns
{
// Client invoking class
public class Client
{
public static void Main()
{
IConnection connection1 = ConnectionFactory.GetConnection(ConnectionType.Sql);
connection1.Connect();

IConnection connection2 = ConnectionFactory.GetConnection(ConnectionType.Oracle);
connection2.Connect();

Console.ReadLine();
}
}

public enum ConnectionType
{
Sql = 0,
Oracle = 1

// Add new Providers
// Provider = 2….
} ;

// Factory class to create objects at runtime based on user selection
public class ConnectionFactory
{

public static IConnection GetConnection(ConnectionType connType)
{
if (connType == ConnectionType.Oracle)
return new OracleConnection();

// need to add more cases if our Connection providers are more
// else if(connType == )
//return new Provider();

// default
return new SqlConnection();
}
}

// Common factory interface for interacting with classes at runtime
public interface IConnection
{
void Connect();
void DisConnect();
}

public class SqlConnection : IConnection
{

#region IConnection Members

public void Connect()
{
Console.WriteLine(“Connected to Sql”);
}

public void DisConnect()
{
Console.WriteLine(“Disconnected from Sql”);
}

#endregion
}

public class OracleConnection : IConnection
{

#region IConnection Members

public void Connect()
{
Console.WriteLine(“Connected to Oracle”);
}

public void DisConnect()
{
Console.WriteLine(“Disconnected from Oracle”);
}

#endregion
}

}

——————————————————————————————————————————————
Abstract Factory Pattern

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace DesignPatterns
{
// Client invoking class
public class Client
{
public static void Main()
{
IBreadFactory indianBreadfactory = new IndianBreadFactory();
IndianVegBread indianVegBread = indianBreadfactory.GetBread(0) as IndianVegBread;
IndianNonVegBread indianNonVegBread = indianBreadfactory.GetBread(1) as IndianNonVegBread;

IBreadFactory americanBreadFactory = new AmericanBreadFactory();
AmericanPlainBread plainBread = americanBreadFactory.GetBread(0) as AmericanPlainBread;
AmericanBreadWithCheese cheeseBread = americanBreadFactory.GetBread(1) as AmericanBreadWithCheese;

Console.ReadLine();
}
}

// Common factory interface for interacting with classes at runtime
public interface IBread
{
void Bake();
}

public interface IBreadFactory
{
IBread GetBread(int i);
}

// First Factory
public class IndianBreadFactory : IBreadFactory
{
public IBread GetBread(int i)
{
IBread bread;
if (i == 0)
bread = new IndianVegBread();

bread = new IndianNonVegBread();
return bread;
}
}

// Second Factory
public class AmericanBreadFactory : IBreadFactory
{
public IBread GetBread(int i)
{
IBread bread;
if (i == 0)
bread = new AmericanPlainBread();

bread = new AmericanBreadWithCheese();
return bread;
}
}

// American Bread products
public class AmericanPlainBread : IBread
{
public void Bake()
{
Console.WriteLine(“American Plain Bread baked”);
}
}

public class AmericanBreadWithCheese : IBread
{
public void Bake()
{
Console.WriteLine(“American Bread With Cheese baked”);
}
}

// Indian Bread Products
public class IndianVegBread : IBread
{
public void Bake()
{
Console.WriteLine(“Indian Veg Bread baked”);
}
}

public class IndianNonVegBread : IBread
{
public void Bake()
{
Console.WriteLine(“Indian Non Veg Bread baked”);
}
}
}

Builder Design Pattern

Posted: December 1, 2010 in Design Patterns

Builder pattern falls under the Creational design pattern. The Builder pattern separates the construction phase of a complex object from its representation so that the same construction logic can be used for different objects and the output representation may be different. Using the same construction logic, we will get different object representations.

I have used the scenario for creation of reports as the example. We can create either PDF or Excel reports. ReportBuilder class has the construction logic for building the individual parts of the Report. Director takes
ReportBuilder as argument and then defines the sequence for building the report. The end result is the Report which can either be Excel or PDF.

The code snippet for this pattern is as seen below :

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace DesignPatterns
{
// Client invoking class
public class Client
{
public static void Main()
{
// Create a PDF report
ReportBuilder pdfBuilder = new PDFBuilder();
Director dir = new Director();
Report pdfReport = dir.GenerateReport(pdfBuilder);

// Print content
Console.WriteLine(pdfReport.Header);
Console.WriteLine(pdfReport.Content);
Console.WriteLine(pdfReport.Footer);

// Create a Excel report
ReportBuilder excelBuilder = new ExcelBuilder();
Report excelReport = dir.GenerateReport(excelBuilder);

// Print content
Console.WriteLine(excelReport.Header);
Console.WriteLine(excelReport.Content);
Console.WriteLine(excelReport.Footer);

Console.ReadLine();
}
}

// Report or Product
public class Report
{
public string ReportType;
public string Header;
public string Footer;
public string Content;

}

// Report Builder – Builder is responsible for defining
// the construction process for individual parts. Builder
// has those individual processes to initialize and
// configure the report.
public abstract class ReportBuilder
{
public Report report;
public void CreateReport()
{
report = new Report();
}
public abstract void SetReportType();
public abstract void SetHeader();
public abstract void SetFooter();
public abstract void SetContent();

public Report DispatchReport()
{
return report;
}

}

// PDF Report class
public class PDFBuilder : ReportBuilder
{

public override void SetReportType()
{
report.ReportType = “PDF”;
}

public override void SetHeader()
{
report.Header = “PDF Header”;
}

public override void SetFooter()
{
report.Footer = “PDF Footer”;
}

public override void SetContent()
{
report.Content = “PDF Content”;
}

}

// Excel Report class
public class ExcelBuilder : ReportBuilder
{

public override void SetReportType()
{
report.ReportType = “Excel”;
}

public override void SetHeader()
{
report.Header = “Excel Header”;
}

public override void SetFooter()
{
report.Footer = “Excel Footer”;
}

public override void SetContent()
{
report.Content = “Excel Content”;
}
}

///

/// Director takes those individual processes from the builder
/// and defines the sequence to build the report.
///

public class Director
{
public Report GenerateReport(ReportBuilder reportBuilder)
{
reportBuilder.CreateReport();
reportBuilder.SetReportType();
reportBuilder.SetHeader();
reportBuilder.SetContent();
reportBuilder.SetFooter();
return reportBuilder.DispatchReport();
}
}
}

Singleton and Prototype patterns fall under Creational Design Patterns which deal with object creation.

Singleton – The purpose behind Singleton pattern is to ensure that one and only instance of the class is present at any time. We usually create the instance of the object on demand i.e delay loading and then ensure that once it is created, no more instances are allowed to be created.

Classical example would be a Menu in case of Winows application. Menu will be common for all pages and we make sure it is not recreated again and again.

Basic fundaa behind singleton is to have a class with private constructor and expose a static getter property which will control the object creation…for first access, object has to be created and then for subsequent access, the same object is returned back. For thread safety purpose, we can use lock.

Prototype pattern – The intent behind the usage of Prototype pattern is for creation of object clone.

The cloning again falls under two categories : shallow and deep. Shallow copy is returned by using MemberwiseClone dotnet method. A shallow copy copies only the elements, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new object point to the same objects that the references in the original object points to. In contrast, a deep copy of an object copies the elements and everything directly or indirectly referenced by the elements.

Example below will explain the difference between shallow and deep clone clearly.

Code for the explanation of both the patterns :

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace DesignPatterns
{
public class CreationalPatterns
{

public static void Main()
{
// Prototype test
ProtoType p = new ProtoType();
TestA a11 = new TestA();
a11.myList.Add(“1”);
a11.myList.Add(“2”);
a11.name = “Testing”;

TestB b11 = new TestB();
b11.i = 10;
a11.b1 = b11;

p.a1 = a11;

ProtoType p1 = p.ShallowClone();
ProtoType p2 = p.DeepClone();

// Both have values copied now change a bit
a11.myList.Add(“3”);
a11.name = “Testing Again after adding 3”;

// Deep copy will show original values whereas
// Shallow copy shows current values
string nameA1 = p1.a1.name;
string nameA2 = p2.a1.name;

// Singleton Test
// At any moment, only and one instance of the Menu is created
MenuInstance menu = MenuInstance.myMenu;

Console.ReadLine();

}
}

// Singleton class – only one instance
// Has private constructor and a property is exposed
// when trying to access the property, check is made if instance
// is already created and if yes, it is returned else instance is created
// and then returned. This is called lazy instantiation.
// Lock is used to prevent thread synchronication issues…if two threads
// try to create instances simultaneously
public class MenuInstance
{
private static MenuInstance _myMenu;
private static object myLock = new object();
private MenuInstance()
{
}

public static MenuInstance myMenu
{
get
{
// Lock is acquired each time we try to access the instance
lock (myLock)
{
if (_myMenu == null)
{
_myMenu = new MenuInstance();
}
}
return _myMenu;
}
}
}

///

/// Prototype pattern implemenatation
///

[Serializable]
public class ProtoType
{

public TestA a1 { get; set; }

// Creates a shallow copy
// Same copy of the referenced object is taken.
// The original object and its clone refer to the same object.
public T ShallowClone()
{
return (T)this.MemberwiseClone(); ;
}

// Creates a deep copy
// A new copy of the referenced object is created
// The original object and its clone refer to different objects.
public T DeepClone()
{
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
T copy = (T) formatter.Deserialize(stream);
stream.Close();
return copy;
}
}

[Serializable]
public class TestA
{
public List myList = new List();
public string name = string.Empty;
public TestB b1;
}

[Serializable]
public class TestB
{
public int i;
}

}

Design Patterns

Posted: November 30, 2010 in Design Patterns

I am great fan of Design pattern and have been trying hard to understand GOF patterns. Design patterns are the solutions to most common problems faced in the software industry. They are proven solutions to a problem and are again scenario dependent. They are just templates for most commonly occuring problems. As a software engineer, we should not try to code according to a specific pattern in our application just to learn it. We are expected to understand the intent behind a specific pattern and then try to fit that pattern into our application based on needs.

They are broadly classified into 3 types :

1. Creational patterns – deals with object instantiation
2. Structural patterns – deals more with object composition to address functionalities.
3. Behavior patterns – deals with communication between objects.

GOF patterns are as listed below :

Creational Patterns

1. Abstract Factory : Creates an instance of several families of classes
2. Builder : Separates object construction from its representation
3. Factory : Creates an instance of several derived classes
4. Prototype : A fully initialized instance to be copied or cloned
5. Singleton : A class of which only a single instance can exist

Structural Patterns

1. Adapter : Match interfaces of different classes
2. Bridge : Separates an object’s interface from its implementation
3. Composite : A tree structure of simple and composite objects
4. Decorator : Add responsibilities to objects dynamically
5. Facade : A single class that represents an entire subsystem
6. Flyweight : A fine-grained instance used for efficient sharing
7. Proxy : An object representing another object

Behavioral Patterns
1. Chain of Resp : A way of passing a request between a chain of objects
2. Command : Encapsulate a command request as an object
3. Interpreter : A way to include language elements in a program
4. Iterator : Sequentially access the elements of a collection
5. Mediator : Defines simplified communication between classes
6. Memento : Capture and restore an object’s internal state
7. Observer : A way of notifying change to a number of classes
8. State : Alter an object’s behavior when its state changes
9. Strategy : Encapsulates an algorithm inside a class
10. Template : Defer the exact steps of an algorithm to a subclass
11. Visitor : Defines a new operation to a class without change