Tuesday, 17 June 2014

Design Pattern 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)rajkumarkarupothula@gmail.com

Design Pattern Explanation

Introduction


Design Patterns (or Implementation Design Patterns to be specific), in the initial stages, was just a set of popular code blocks often communicated between developers or Application designers without specific coined terms.
That is the time when four people authored a book on these popular often-used code blocks of implementation design, and made the term / coined word "Design Patterns" popular. These people come to be referred to as Gang Of Four.
The point of telling that History again, which most possibly you have already read / heard a 100 times, is that, the patterns we discuss in this article are going to be from the Gang Of Four list of Design Patterns.
Over the years, many more design patterns have become popular, either new ones or variations to the published standard patterns referred in the book by the four people. In other words, this article is not going to be able to discuss a complete list of design patterns.

Getting to Know Design Patterns

Almost all patterns basically can be considered good examples of Object Oriented Programming... that means implementing design patterns requires good knowledge/experience with OOPs.

Interfaces & Classes

In OOP we have learnt that Classes can implement Interfaces... and that it is best for classes to do so because the Interface then provides the structure / methods that the Class should implement in its code, like a rule book.
So developers of the Class don't miss something, and creators of the Interface have a structured mechanism to make Class developers adhere to rules.
And these rules / interfaces can then become a common rule which many Classes implement in the same library or application.
The same with having abstract classes defining an abstraction, for a class to then inherit and apply.
Most Design Patterns will use Interfaces, Abstract Classes and Classes to implement Abstraction, Separation, and Rules. We will see more of it.

An Implementation Pattern

An example:
interface ITelephone
{
    void MakeCall(string PhoneNumber);
    void Receivecall();
}

class Phone : ITelephone
{
    public void MakeCall(string PhoneNumber) 
    {
        //some implementation to make a call
    }
    public void Receivecall() 
    { 
        //some implementation to receive a call
    }
}  
In the above example, the ITelephone interface defines a rule.. which the implementation class Phone uses.
Now, going below the surface, the real advantage of building classes & interfaces come to play only when we have much more of them... like below:
public interface ITelephone
{
      void MakeCall(string PhoneNumber);
      void Receivecall();
}

public interface ISMSDevice
{
     void SendSms(string PhoneNumber, string Message);
     void ReceiveSms();
}

public interface IMobileDevice
{
    void SetDateTime();
    void ChangeTimeZone();
    void SetReminderAlert();
    void GetContacts();
    void AddContact();
}

class Phone : ITelephone
{
     public void MakeCall(string PhoneNumber) 
     {
         //some implementation to make a call
     }

     public void Receivecall() 
     { 
         //some implementation to receive a call
     }
}

class MobilePhone : ITelephone, ISMSDevice
{
      public void MakeCall(string PhoneNumber)
      {
           //some implementation to make a call
      }

      public void Receivecall()
      {
           //some implementation to receive a call
      }

      public void SendSms(string PhoneNumber, string Message)
      {
           // implementation 
      }
      public void ReceiveSms()
      {
           // implementation
      }
}
The above code shows how interfaces can define different rules while classes implement them.
The rules (given by interfaces) and the creation process (given by classes) are isolated... so that the same Creation process can be used to create various representations of the object.. like a Phone and a Mobile Phone both implementing the core features of a Telephone.
The above code implementation is called a Builder Pattern... because it lays down a pattern for makingbuilding blocks.

Using the Builder Pattern

//The usage class
public class PhoneServices
{
    public void CallNumber(ITelephone Device)
    {
        Device.MakeCall("9278349082");
    }
}

//The create and use class
class Myclass
{
    public void RingAContact()
    {
        PhoneServices ph1 = new PhoneServices();
        ITelephone phone = new MobilePhone();

        ph1.CallNumber(phone);
    }
}
  1. A PhoneServices class, implements logic, to do operations (like CallNumber()) on different objects (Phone or MobilePhone instances which are both ITelephone Devices) with the same code, because the objects implement common interfaces (ITelephone).
    I will call the PhoneServices class a “Usage” class, because it doesn't implement the design but only uses it. So that a Client Class (which I will call as “Create & Use” class), MyClass, can create instances of a Phone / Mobile Phone and call the CallNumber() method.
  2. If a need arises later to make a new type of Phone like the PDA, then relevant new interface and implementation can be developed... and the PDA class can implement both existing and new interfaces without necessarily modifying existing code.

Isn't it easier to code simply without much interfaces / classes, so you don't have to bother about maintaining all of that ?

The idea of builder pattern, or any other design pattern is the idea of OOP itself.
It is similar to isolating the Human Body into skeleton and muscle... so that it helps separate Development teams take care of each block of implementation, like making the skeleton (An Interface), separated from wrapping the muscle (A Class) around it... so the muscle team doesn't have to understand everything about the structure of the human body, but they have to just follow the connection points (Interface Definition) in the skeleton and add the muscle.
In other ways, the skeleton (Interface) team wouldn't bother what implementation (Class) the muscle team does... it only states the mandatory structures (Interface Definition) required.

Object Oriented Programming

When we are making something so complex as the Human Body, we can't expect everything to be understood by every person on a Team. Right from the requirements, to design, to the implementation and testing, things have to be split.
The development has to be modularized (as Objects), to keep things tight and isolate people's tasks, to allow them to focus on every bit and inch of what is being developed.
There can further be a blood vessels team, a nerves team, etc., who, then, bother only about the design of things in their scope.. so that, finally a Creator team, can implement code, which uses instances of all these design blocks, to make the full human body. The Creator team technically acts like the user of all the Building blocks.

An Adaptation

Let us make some crude but interesting real life scenario assumptions.
Assume that we rolled out a product which contains our builder pattern example code... and lot of companies bought the product and implemented it into real phone and mobile devices to allow the device to make calls, receive calls, send SMS, etc.
Now we have been requested by a laptop manufacturer to provide software to allow a laptop to provide phone services through one of its in-built hardware... but the laptop's hardware provides different communication ports or mechanisms different from a phone or a mobile device. We want to adapt our library to be useful here, at the same time not change any existing code because we sell the same telephone library already to phone companies.
What we would then do is .. typically make an adapter class... which will convert phone calls to laptop based communication... as below.
// The class in a laptop's library which does laptop communications
    public class Laptop
    {
        public void OpenVoiceSocket()
        {

        }

        public void SendVoiceData()
        {

        }
    }

// The adaptor class that is added to our library in a separate class file.
    public class LaptopAdaptor : ITelephone
    {
        private Laptop computer1 = new Laptop();

        public void MakeCall(string number)
        {
            computer1.OpenVoiceSocket();
            computer1.SendVoiceData();
        }

        public void Receivecall()
        {

        }
    }
As you see above, the two classes can be part of entirely different libraries which are released by different companies, one by you (LaptopAdaptor), and another by the Laptop company.
The Adaptation is done in the LaptopAdaptor class which shall go into our phone library as a new class without disturbing existing code. The LaptopAdaptor class converts Phone operations into Laptop communication operations by calling Laptop communication methods.
This is called an Adapter Pattern.

Splitting up Implementation and Adding Bridges

Now, let us change some of our old code in a different way. If we change our earlier phone example to something like below.... keeping the ITelephone and ISmsDevice interfaces, and rewriting everything else.
    public class GenericPhone : ITelephone
    {
        public void MakeCall(string PhoneNumber)
        {
            //implementation for making a call
        }

        public void Receivecall()
        {
            //implementation for receiving a call
        }
    }

    public class GenericSMS : ISMSDevice
    {
        public void SendSms(string PhoneNumber, string Message)
        {

        }

        public void ReceiveSms()
        {

        }
    }

    public interface IPhone
    {
        void MakePhoneCall(string PhoneNumber);
        void SendMessage(string PhoneNumber, string Message);
    }

    public class MobilePhone : IPhone
    {
        private GenericPhone phone;
        private GenericSMS smsDevice;

        public MobilePhone(GenericPhone DeviceHandle1, GenericSMS DeviceHandle2)
        {
            this.phone = DeviceHandle1;
            this.smsDevice = DeviceHandle2;
        }

        public void MakePhoneCall(string PhoneNumber)
        {
            phone.MakeCall(PhoneNumber);
        }

        public void SendMessage(string PhoneNumber, string Message)
        {
            smsDevice.SendSms(PhoneNumber, Message);
        }
    }

    // Client code
    static void MakePhoneCall()
    {
       IPhone userPhone = new MobilePhone(new GenericPhone(), new GenericSMS());
       userPhone.MakePhoneCall("234234");
    }
We arrive at a different implementation. In the Builder Pattern, we kept all implementation logic inside thePhone and MobilePhone classes... and actually the implementation for MakeCall and ReceiveCall are repetitive. That repetition is ok for some designs.
To avoid repetition and manage changes easily at one place, we can split implementation into multiple layers, like in this code above... which shows how it helps put MakeCall() implementation in one place. But, this is needed only if the project is big and has lot of operations to be made abstract. On small projects, too many layers of abstraction will make the code complex and heavy on maintenance.
The above code separates some amount of implementation (example: MakeCall, SendSms methods), into another set of classes (GenericPhone and GenericSmsDevice). This demonstrates not just separation of design rules and implementation, but separates the implementation part into a core implementation and operations implementation.
Now the operational code (example: MobilePhone) are delinked from the implementation code (example:GenericPhone)... and finally kind of making a bridge between the operations and the implementation, the above code makes for an example of the Bridge Pattern.
The main advantage of Bridge Pattern over Builder Pattern is it isolates changes to core implementation from affecting the operational code (the bridge classes).
Some day, if the implementation to making a phone call changes, or has some additional work to be done like formatting the phone numbers before making the call, to fix a bug, then the bridge classes need not be touched.. only the core implementation classes need to undergo modifications and testing.

Making a Mediator

Suppose we have a scenario, that our company also had a team which developed a fax messaging library, and an emailing library.. and we want to bring them together, to finally make a full communications system.
And say that different messages can come to the same processing module in the communications block implementation, which then processes / sends the messages appropriately, based on whether it is an email request or an SMS request or a fax request.
Then we can call the central block of code that handles this as a Mediator... and the entire system to be having a Mediator pattern... the other blocks like phone module, the fax module could be developed in different patterns.
Enough of scenario assumption.. it is something like the below code, assuming FaxDevice is a class implementation in another referenced library in the project
public class Communicator
    {

        public void SendMessage(string Message, string PhoneNumber, string Mode)
        {
            switch (Mode.ToUpper())
            {
                case "FAX":
                    FaxDevice faxer1 = new FaxDevice();
                    faxer1.SendFax(Message, PhoneNumber);
                    break;

                case "SMS":
                    MobilePhone phone1 = new MobilePhone();
                    phone1.SendMessage(PhoneNumber, Message);

            }
        }
    }

// Usage code
Communicator commChannel = new Communicator();
commChannel.SendMessage("Fire in Deck 01A! ", "+11232342323452", "EMAIL");
The above usage code can be part of some module or library which has no idea of existence of aMobilePhone class or a FaxDevice class... but still can send messages on the devices through the Mediator.
Mediator patterns are most useful in integrating two or more systems, or blocks of implementation (B1, B2, … Bn) which are independent of each other, and can't allow calling each other or be aware of each other.
Examples are like integrating with a 3rd party library, or co-ordinating legacy systems with new system code, etc.

Confused with Different Patterns?

How to remember which pattern should be implemented with an interface and which with an abstract class?

Did you notice that I have used a switch statement in the above example to implement the Mediator pattern? Does that makes it more an Intercepting Filter pattern than a mediator Pattern?
Well, this is the part I love about Design Patterns...
Any Design Pattern you implement could possibly have other patterns inside it.. like you can implement Mediator pattern using a Bridge, or use an Adapter to implement a Bridge, etc.
It all depends on your code.. there is no rule that Builder patterns should use Interfaces (you can use abstractclasses in place of the interfaces), and no rule that you should not use an Intercepting Filter to implement your Mediator.
It will not be interesting to implement a pattern using the same kind of code you find in this article or elsewhere... but it will be interesting when you understand that a mediator pattern it becomes, when you write a separate layer to mediate between two independent blocks... and a bridge pattern it becomes when you separate operational code (or Operations calls to do work) from actual implementation (the actual implementation code) with abstractions on either side... like that.
I am going to leave it here with patterns and examples, but there are more design patterns both in the Gang of Four book and outside of it in the software community.

Different Pattern Categories

There is one other thing we didn't discuss so far. They are Pattern Categories.
Generally, Patterns are categorized into three buckets.. Creational, Structural and Behavioral Patterns.
We have discussed the Builder Pattern which is a Creational pattern, because of its logic being more interested in setting creational rules for Building blocks without separating stuff into layers.
We have discussed the Adapter Pattern and Bridge Pattern, which come under Structural Patterns, because they separate stuff into layers thereby adding a structure to different classes sharing the implementation.
We have discussed the Mediator Pattern which is a Behavioral pattern, because it gives more importance towards implementing the mediating behavior for a class.

Conclusion

There are many more patterns which are further put into the different categories for making it a little easier to decide when to use which kind of pattern.
But, there will be code that implements a structural design pattern, seemingly using a behavioral pattern, and the like. Mixing and matching the patterns to implement requirements is most often a necessity.
This article misses a lot of graphical representation, using UML and block diagrams, which could have made it more clearer and beautiful to visualize... I will try to add them soon. Meanwhile you can use some the below interesting reference links for further clarity.
I hope this article was useful.. please leave your comments, thoughts and feedback.

Reference Links