13 April 2014

Bridge Design Pattern -- Design Pattern

    Decouple an abstraction from its implementation so that the two can vary independently.


Participants

   The classes and/or objects participating in this pattern are:
  • Abstraction(Business Object)
         Defines the abstraction's interface.Maintains a reference to an object of type Implementer.
  • Refined Abstraction   (Customers Business Object)
          Extends the interface defined by Abstraction.
  • Implementer(Data Object)
         Defines the interface for implementation classes. This interface doesn't have to correspond exactly to Abstraction's interface; in fact the two interfaces can be quite different. Typically the Implementation interface provides only primitive operations, and Abstraction defines higher-level operations based on these primitives.
  • Concrete Implementer(Customers Data Object)
         Implements the Implementer interface and define its concrete implementation.

Sample Code:

// Bridge pattern -- Structural example

using System; 
Namespace Bridge. Structural
{
  /// <summary>
  /// MainApp startup class for Structural
  /// Bridge Design Pattern.
  /// </summary>
  class MainApp
  {
    /// <summary>
    /// Entry point into console application.
    /// </summary>
    static void Main()
    {
      Abstraction ab = new RefinedAbstraction();

      // Set implementation and call
      ab.Implementor = new ConcreteImplementorA();
      ab.Operation();

      // Change implemention and call
      ab.Implementor = new ConcreteImplementorB();
      ab.Operation(); 
      // Wait for user
      Console.ReadKey();
    }
  } 
  /// <summary>
  /// The 'Abstraction' class
  /// </summary>
  class Abstraction
  {
    protected Implementor implementor; 
    // Property
    public Implementor Implementor
    {
      set { implementor = value; }
    } 
    public virtual void Operation()
    {
      implementor.Operation();
    }
  } 
  /// <summary>
  /// The 'Implementor' abstract class
  /// </summary>
  abstract class Implementor
  {
    public abstract void Operation();
  } 
  /// <summary>
  /// The 'RefinedAbstraction' class
  /// </summary>
  class RefinedAbstraction : Abstraction
  {
    public override void Operation()
    {
      implementor.Operation();
    }
  }

  /// <summary>
  /// The 'ConcreteImplementorA' class
  /// </summary>
  class ConcreteImplementorA : Implementor
  {
    public override void Operation()
    {
      Console.WriteLine("ConcreteImplementorA Operation");
    }
  } 
  /// <summary>
  /// The 'ConcreteImplementorB' class
  /// </summary>
  class ConcreteImplementorB : Implementor
  {
    public override void Operation()
    {
      Console.WriteLine("ConcreteImplementorB Operation");
    }
  }
}

Output
ConcreteImplementorA Operation
ConcreteImplementorB Operation


No comments:

Post a Comment