Introduction
Design patterns may be said as a set of probable solutions for a particular problem which is tested to work best in certain situations. In other words, Design patterns, say you have found a problem. Certainly, with the evolution of software industry, most of the others might have faced the same problem once. Design pattern shows you the best possible way to solve the recurring problem.
Uses of Design Patterns
While creating an application, we think a lot on how the software will behave in the long run. It is very hard to predict how the architecture will work for the application when the actual application is implemented completely. There might issues which you cant predict and may come while implementing the software. Design patterns helps you to find tested proven design paradigm to build a solid foundation for your project. So, if you follow design pattern you can easily prevent major issues to come while building your actual project. Moreover design pattern also helps the other architects to understand your code easily.
History of Design Patterns
When the word design pattern comes into mind, the first thing that one may think is the classical book on Design Pattern "Gangs of Four" which was published by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. In this book, it is first discussed capabilities and pitfalls of Object oriented programming, and later on it discusses about the classic Design Patterns on OOPS.
You can read more about history of design patterns from here.
Types of Design Pattern
Design patterns can be divided into 3 categories.
- Creational Patterns : These patterns deals mainly with creation of objects and classes.
- Structural Patterns : These patterns deals with Class and Object Composition.
- Behavioural Patterns : These mainly deals with Class - Object communication. That means they are concerned with the communication between class and objects.
In this article, I am going to discuss few examples of these patterns. They are
- Singleton Design Pattern
- Factory Design Pattern
- Factory Method Design Pattern
- Abstract Factory Design Pattern,
- Builder Design Pattern,
- Prototype Design Pattern
- Adapter Design Pattern
- Bridge Design Pattern
- Decorator Design Pattern
- Composite Design Pattern
- Flyweight Design Pattern
- Memento Design Pattern
- Mediator Design Pattern
- Observer Design Pattern
- Iterator Pattern
CREATIONAL PATTERNS
Singleton Pattern
Singleton pattern creates a class which can have a single object throughout the application, so that whenever any other object tries to access the object of the class, it will access the same object always.
///In the above code you can see I have intentionally made the constructor as private. This will make sure that the class cant be instantiated from outside. On the other hand, you also need to make a property which will return the static instance of the object present within the class itself. Hence the object will be shared between all the external entities.
/// Implementation of Singleton Pattern
///
public sealed class SingleTon
{
private static SingleTon _instance = null; private SingleTon() // Made default constructor as private { } /// /// Single Instance /// public static SingleTon Instance {
get {
lock (_instance)
{
_instance = _instance ?? new SingleTon(); return _instance;
} }
} # region Rest of Implementation Logic //Add As many method u want here as instance member.No need to make them static # endregion
}
Factory Pattern
Factory pattern deals with the instantiation of object without exposing the instantiation logic. In other words, a Factory is actually a creator of object which has common interface.
//Empty vocabulary of Actual objectpublic interface IPeople
{
string GetName();
} public class Villagers : IPeople
{
#region IPeople Members public string GetName() {
return "Village Guy";
} #endregion
}public class CityPeople : IPeople {
#region IPeople Members public string GetName() {
return "City Guy";
} #endregion
}public enum PeopleType {
RURAL, URBAN
}/// /// Implementation of Factory - Used to create objects /// public class Factory {
public IPeople GetPeople(PeopleType type) {
IPeople people = null; switch (type) {
case PeopleType.RURAL:
people = new Villagers();
break; case PeopleType.URBAN:
people = new CityPeople();
break;
default:
break;
} return people;
}
}
In the above code you can see I have created one interface called IPeople and implemented two classes from it as Villagers and CityPeople. Based on the type passed into the factory object, I am sending back the original concrete object as the Interface IPeople.
Factory Method
A Factory method is just an addition to Factory class. It creates the object of the class through interfaces but on the other hand, it also lets the subclass to decide which class to be instantiated.
public interface IProduct
{
string GetName(); string SetPrice(double price);
} public class IPhone : IProduct {
private double _price; #region IProduct Members public string GetName() {
return "Apple TouchPad";
} public string SetPrice(double price) {
this._price = price; return "success";
} #endregion
} /* Almost same as Factory, just an additional exposure to do something with the created method */ public abstract class ProductAbstractFactory {
public IProduct DoSomething() {
IProduct product = this.GetObject(); //Do something with the object after you get the object. product.SetPrice(20.30); return product;
}
public abstract IProduct GetObject();
}
public class ProductConcreteFactory : ProductAbstractFactory
{
public override IProduct GetObject() // Implementation of Factory Method.
{
return this.DoSomething();
}
}
You can see I have used GetObject in concreteFactory. As a result, you can easily call DoSomething() from it to get the IProduct.
You might also write your custom logic after getting the object in the concrete Factory Method. The GetObject is made abstract in the Factory interface.
You might also write your custom logic after getting the object in the concrete Factory Method. The GetObject is made abstract in the Factory interface.
Abstract Factory
Abstract factory is the extension of basic Factory pattern. It provides Factory interfaces for creating a family of related classes. In other words, here I am declaring interfaces for Factories, which will in turn work in similar fashion as with Factories.
public interface IFactory1
{
IPeople GetPeople();
} public class Factory1 : IFactory1 {
public IPeople GetPeople() {
return new Villagers();
}
} public interface IFactory2 {
IProduct GetProduct();
}
public class Factory2 : IFactory2
{
public IProduct GetProduct() { return new IPhone(); }
} public abstract class AbstractFactory12 {
public abstract IFactory1 GetFactory1(); public abstract IFactory2 GetFactory2();
} public class ConcreteFactory : AbstractFactory12 {
public override IFactory1 GetFactory1() {
return new Factory1();
} public override IFactory2 GetFactory2() {
return new Factory2();
}
}
The factory method is also implemented using common interface each of which returns objects.
Builder Pattern
This pattern creates object based on the Interface, but also lets the subclass decide which class to instantiate. It also has finer control over the construction process. There is a concept of Director in Builder Pattern implementation. The director actually creates the object and also runs a few tasks after that.
public interface IBuilder
{
string RunBulderTask1(); string RunBuilderTask2();
} public class Builder1 : IBuilder {
#region IBuilder Members public string RunBulderTask1() {
throw new ApplicationException("Task1");
} public string RunBuilderTask2() {
throw new ApplicationException("Task2");
} #endregion
} public class Builder2 : IBuilder {
#region IBuilder Members public string RunBulderTask1() {
return "Task3";
} public string RunBuilderTask2() {
return "Task4";
} #endregion
} public class Director {
public IBuilder CreateBuilder(int type) {
IBuilder builder = null; if (type == 1)
builder = new Builder1();
else builder = new Builder2(); builder.RunBulderTask1(); builder.RunBuilderTask2(); return builder;
}
}
In case of Builder pattern you can see the Director is actually using CreateBuilder to create the instance of the builder. So when the Bulder is actually created, we can also invoke a few common task in it.
Prototype Pattern
This pattern creates the kind of object using its prototype. In other words, while creating the object of Prototype object, the class actually creates a clone of it and returns it as prototype.
public abstract class Prototype
{
// normal implementation public abstract Prototype Clone();
} public class ConcretePrototype1 : Prototype {
public override Prototype Clone() {
return (Prototype)this.MemberwiseClone();
}
} class ConcretePrototype2 : Prototype {
public override Prototype Clone() {
return (Prototype)this.MemberwiseClone(); // Clones the concrete class.
}
}
You can see here, I have used MemberwiseClone method to clone the prototype when required. You must remember, MemberwiseClone is actually a swallow copy. To make it copy deep, you need to call MemberwiseClone recursively for every object until its value types.
STRUCTURAL PATTERN
Adapter Pattern
Adapter pattern converts one instance of a class into another interface which client expects. In other words, Adapter pattern actually makes two classes compatible.
public interface IAdapter
{
/// /// Interface method Add which decouples the actual concrete objects ///
void Add();
} public class MyClass1 : IAdapter {
public void Add() { }
} public class MyClass2 {
public void Push() { }
} /// /// Implements MyClass2 again to ensure they are in same format. /// public class Adapter : IAdapter {
private MyClass2 _class2 = new MyClass2(); public void Add() {
this._class2.Push();
}
}
Here in the structure, the adapter is used to make MyClass2 incompatible with IAdapter.
Bridge Pattern
Bridge pattern compose objects in tree structure. It decouples abstraction from implementation. Here abstraction represents the client where from the objects will be called.
# region The Implementation
///
/// Helps in providing truely decoupled architecture
///
public interface IBridge
{
void Function1();
void Function2();
} public class Bridge1 : IBridge {
#region IBridge Members public void Function1() {
throw new NotImplementedException();
} public void Function2() {
throw new NotImplementedException();
} #endregion
} public class Bridge2 : IBridge {
#region IBridge Members public void Function1() {
throw new NotImplementedException();
} public void Function2() {
throw new NotImplementedException();
} #endregion
} # endregion # region Abstraction public interface IAbstractBridge {
void CallMethod1(); void CallMethod2();
} public class AbstractBridge : IAbstractBridge {
public IBridge bridge; public AbstractBridge(IBridge bridge) {
this.bridge = bridge;
} #region IAbstractBridge Members public void CallMethod1() {
this.bridge.Function1();
} public void CallMethod2() {
this.bridge.Function2();
} #endregion
} # endregion
Thus you can see the Bridge classes are the Implementation, which uses the same interface oriented architecture to create objects. On the other hand the abstraction takes an object of the implementation phase and runs its method. Thus makes it completely decoupled with one another.
Decorator Pattern
Decorator pattern is used to create responsibilities dynamically. That means each class in case of Decorator pattern adds up special characteristics.In other words, Decorator pattern is the same as inheritance.
public class ParentClass
{
public void Method1() { }
} public class DecoratorChild : ParentClass {
public void Method2() { }
}
This is the same parent child relationship where the child class adds up new feature called Method2 while other characteristics is derived from the parent.
Composite Pattern
Composite pattern treats components as a composition of one or more elements so that components can be separated between one another. In other words, Composite patterns are those for whom individual elements can easily be separated.
///
/// Treats elements as composition of one or more element,
///so that components can be separated
/// between one another
///
public interface IComposite
{
void CompositeMethod();
} public class LeafComposite : IComposite {
#region IComposite Members public void CompositeMethod() {
//To Do something
} #endregion
} /// /// Elements from IComposite can be separated from others /// public class NormalComposite : IComposite {
#region IComposite Members public void CompositeMethod() {
//To Do Something
} #endregion public void DoSomethingMore() {
//Do Something more .
}
}
Here in the code you can see that in NormalComposite, IComposite elements can easily be separated.
Flyweight Pattern
Flyweight allows you to share bulky data which are common to each object. In other words, if you think that same data is repeating for every object, you can use this pattern to point to the single object and hence can easily save space.
////// Defines Flyweight object which repeats iteself. /// public class FlyWeight {
public string Company { get; set; } public string CompanyLocation { get; set; } public string CompanyWebSite { get; set; } //Bulky Data public byte[] CompanyLogo { get; set; }} public static class FlyWeightPointer {
public static FlyWeight Company = new FlyWeight {} public class MyObject {
Company = "Abc", CompanyLocation = "XYZ", CompanyWebSite = "www.abc.com"};
public string Name { get; set; } public FlyWeight Company {}
get {}
return FlyWeightPointer.Company;}
Here the FlyweightPointer creates a static member Company, which is used for every object of MyObject.
Memento Pattern
Memento pattern allows you to capture the internal state of the object without violating encapsulation and later on you can undo/ revert the changes when required.
public class OriginalObject
{
public string String1 { get; set; }
public string String2 { get; set; }
public Memento MyMemento { get; set; }
public OriginalObject(string str1, string str2)
{
this.String1 = str1;
this.String2 = str2;
this.MyMemento = new Memento(str1, str2);
}
public void Revert()
{
this.String1 = this.MyMemento.String1;
this.String2 = this.MyMemento.String2;
}
}
public class Memento
{
public string String1 { get; set; }
public string String2 { get; set; }
public Memento(string str1, string str2)
{
this.String1 = str1;
this.String2 = str2;
}
}
Here you can see the Memento Object is actually used to Revert the changes made in the object.
BEHAVIOURAL PATTERN
Mediator Pattern
Mediator pattern ensures that the components are loosely coupled, such that they don't call each others explicitly, rather they always use a separate Mediator implementation to do those jobs.
public interface IComponent
{
void SetState(object state);
} public class Component1 : IComponent {
#region IComponent Members public void SetState(object state) {
//Do Nothing throw new NotImplementedException();
} #endregion
} public class Component2 : IComponent {
#region IComponent Members public void SetState(object state) {
//Do nothing throw new NotImplementedException();
} #endregion
} public class Mediator // Mediages the common tasks {
public IComponent Component1 { get; set; } public IComponent Component2 { get; set; } public void ChageState(object state) {
this.Component1.SetState(state); this.Component2.SetState(state);
}
}
Here you can see the Mediator Registers all the Components within it and then calls its method when required.
Observer Pattern
When there are relationships between one or more objects, an observer will notify all the dependent elements when something is modified in the parent. Microsoft already implemented this pattern as ObservableCollection. Here let me implement the most basic Observer Pattern.
public delegate void NotifyChangeEventHandler(string notifyinfo); public interface IObservable { void Attach(NotifyChangeEventHandler ohandler);
void Detach(NotifyChangeEventHandler ohandler);
void Notify(string name);
} public abstract class AbstractObserver : IObservable {
public void Register(NotifyChangeEventHandler handler) {
this.Attach(handler);
} public void UnRegister(NotifyChangeEventHandler handler) {
this.Detach(handler);
} public virtual void ChangeState() {
this.Notify("ChangeState");
} #region IObservable Members public void Attach(NotifyChangeEventHandler ohandler) {
this.NotifyChanged += ohandler;
} public void Detach(NotifyChangeEventHandler ohandler) {
this.NotifyChanged -= ohandler;
} public void Notify(string name) {
if (this.NotifyChanged != null) this.NotifyChanged(name);
} #endregion #region INotifyChanged Members public event NotifyChangeEventHandler NotifyChanged; #endregion
} public class Observer : AbstractObserver {
public override void ChangeState() {
//Do something. base.ChangeState();
}
}
You can definitely got the idea that after you Register for the Notification, you will get it when ChangeState is called.
Iterator Pattern
This pattern provides a way to access elements from an aggregate sequentially. Microsoft's IEnumerable is one of the example of this pattern. Let me introduce this pattern using this interface.
public class Element
{
public string Name { get; set; }
} public class Iterator : IEnumerable<Element> {
public Element[] array; public Element this[int i] {
get {
return array[i];
}
}
#region IEnumerable Members public IEnumerator<Element> GetEnumerator() {
foreach (Element arr in this.array) yield return arr;
} #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
foreach (Element arr in this.array) yield return arr;
} #endregion
}
In the above code you can see I have implemented IEnumerable which actually corresponds to the Iterator block. You can also implement it yourself, just by adding few methods like First(), Last(), Next() etc. As they are already implemented as extension method with IEnumerable, I have just made it simpler using it.
Conclusion
These are the most basic design patterns that we often use. Of course, there are others. I will try to update with them too in near future. Please don't forget to criticize me or give comments if you find anything interesting or any mistake in the implementation. I will definitely update the article.
Thank you for reading. Happy Programming.
Download
by Abhi2434
nice article
ReplyDelete