Design Patterns in C#

As I am doing a lot of architecture stuffs, lets discuss the very basics of designing a good architecture. To begin with this, you must start with Design patterns.

What is Design Patterns ?

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 built 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. Following design pattern will prevent major issues to come in future and also helps the other architects to easily understand your code.

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.

Types of Design Pattern

Design patterns can be divided into 3 categories.
  1. Creational Patterns : These patterns deals mainly with creation of objects and classes.
  2. Structural Patterns : These patterns deals with Class and Object Composition.
  3. 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.

You can Read the entire article from
http://www.dotnetfunda.com/articles/article889-design-pattern-implementation-using-csharp-.aspx

or
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.



Implementation
/// <summary>
    /// Implementation of Singleton Pattern
    /// </summary>
    public sealed class SingleTon
    {
        private static SingleTon _instance =null;
        private SingleTon() // Made default constructor as private 
        {
        }
        /// <summary>
        /// Single Instance
        /// </summary>
        public static SingleTon Instance 
        {
            get
            {
                lock (_instance)
                {
                    _instance = _instance ?? new SingleTon();
                    return _instance;
                }
            }
        }

        # region Rest of Implementation Logic

        //Add As many method as u want here as instance member. No need to make them static.

        # endregion
    }

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.

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.



Implementation

//Empty vocabulary of Actual object
    public 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
    }

    /// <summary>
    /// Implementation of Factory - Used to create objects
    /// </summary>
    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.


IMPLEMENTATION

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.

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.


IMPLEMENTATION

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.




IMPLEMENTATION

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.



IMPLEMENTATION

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.



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.






IMPLEMENTATION

public interface IAdapter
    {
        /// <summary>
        /// Interface method Add which decouples the actual concrete objects
        /// </summary>
        void Add();
    }
    public class MyClass1 : IAdapter
    {
        public void Add()
        {
        }
    }
    public class MyClass2
    {
        public void Push()
        {

        }
    }
    /// <summary>
    /// Implements MyClass2 again to ensure they are in same format.
    /// </summary>
    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.



IMPLEMENTATION

# region The Implementation
    /// <summary>
    /// Helps in providing truely decoupled architecture
    /// </summary>
    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 patter adds up special characteristics.In other words, Decorator pattern is the same as inheritance.



IMPLEMENTATION

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.

IMPLEMENTATION

/// <summary>
    /// Treats elements as composition of one or more element, so that components can be separated
    /// between one another
    /// </summary>
    public interface IComposite
    {
        void CompositeMethod();
    }

    public class LeafComposite :IComposite 
    {

        #region IComposite Members

        public void CompositeMethod()
        {
            //To Do something
        }

        #endregion
    }

    /// <summary>
    /// Elements from IComposite can be separated from others 
    /// </summary>
    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.

IMPLEMENTATION

/// <summary>
    /// Defines Flyweight object which repeats iteself.
    /// </summary>
    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
        {
            Company = "Abc",
            CompanyLocation = "XYZ",
            CompanyWebSite = "www.abc.com"
        };
    }
    public class MyObject
    {
        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.

IMPLEMENTATION

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.


IMPLEMENTATION

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.






IMPLEMENTATION

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.






IMPLEMENTATION


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<element> 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
    }


Download Source code here

OR

DesignPatterns.zip (55.3 KB)

Conclusion

These are the basic design patterns. There are still few design patterns left to be implemented. Stay tuned for those updates.
Thank you for reading.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

4 comments:

Kunal Chowdhury said...

Good one... :thumsup:

Regards,
Kunal

Abhishek Sur said...

Thank you kunal.

Pallab said...

Well explained design pattern..

Abhishek Sur said...

Thanks pallab. :)

Post a Comment

Please make sure that the question you ask is somehow related to the post you choose. Otherwise you post your general question in Forum section.

Author's new book

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!