Monday, July 18, 2011

Bridge Pattern


The bridge pattern is a design pattern which is meant to "decouple an abstraction from its implementation so that the two can vary independently". The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.

When a class varies often, the features of object-oriented programming become very useful because changes to a program's code can be made easily with minimal prior knowledge about the program. The bridge pattern is useful when both the class as well as what it does vary often. The class itself can be thought of as the implementation and what the class can do as the abstraction. The bridge pattern can also be thought of as two layers of abstraction.
The bridge pattern is often confused with the adapter pattern. In fact, the bridge pattern is often implemented using the class adapter pattern, e.g. in the Java code below.
Variant: The implementation can be decoupled even more by deferring the presence of the implementation to the point where the abstraction is utilized.

Intent
Decouple an abstraction from its implementation so that the two can vary independently.
Publish interface in an inheritance hierarchy, and bury implementation in its own inheritance hierarchy. Beyond encapsulation, to insulation

Problem
Hardening of the software arteries” has occurred by using subclassing of an abstract base class to provide alternative implementations. This locks in compile-time binding between interface and implementation. The abstraction and implementation cannot be independently extended or composed.

Motivation
Consider the domain of “thread scheduling”.



There are two types of thread schedulers, and two types of operating systems or “platforms”. Given this approach to specialization, we have to define a class for each permutation of these two dimensions. If we add a new platform (say … Java’s Virtual Machine), what would our hierarchy look like?



What if we had three kinds of thread schedulers, and four kinds of platforms? What if we had five kinds of thread schedulers, and ten kinds of platforms? The number of classes we would have to define is the product of the number of scheduling schemes and the number of platforms.
The Bridge design pattern proposes refactoring this exponentially explosive inheritance hierarchy into two orthogonal hierarchies – one for platform-independent abstractions, and the other for platform-dependent implementations.



Another example can be seen like that-
Inheritance hierarchies can be hierarchies of abstarctions (concepts) or hierarchies of implementations. For example: 



Mixing concepts with implementations can lead to hierarchies that are confusing and difficult to maintain.
It could lead to an exponential number of subclasses and soon we will have an exploding class hierarchy.

Discussion

Decompose the component’s interface and implementation into orthogonal class hierarchies. The interface class contains a pointer to the abstract implementation class. This pointer is initialized with an instance of a concrete implementation class, but all subsequent interaction from the interface class to the implementation class is limited to the abstraction maintained in the implementation base class. The client interacts with the interface class, and it in turn “delegates” all requests to the implementation class.
The interface object is the “handle” known and used by the client; while the implementation object, or “body”, is safely encapsulated to ensure that it may continue to evolve, or be entirely replaced (or shared at run-time.

Use the Bridge pattern when:

  • you want run-time binding of the implementation,
  • you have a proliferation of classes resulting from a coupled interface and numerous implementations,
  • you want to share an implementation among multiple objects,
  • you need to map orthogonal class hierarchies.
  • You want to avoid a permanent binding between an abstraction and its implementation.
  • Both the abstractions and their implementations should be extensible by subclassing
  • Changes in the implementation of an abstraction should have no impact on clients – their code should not have to be recompiled
  • (C++) you want to hide the implementation of an abstraction completely from clients (in C++, the representation of a class is visible in the class interface)
  • You have a proliferation of classes as shown earlier in the motivation.





    Consequences include:

    • decoupling the object’s interface,
    • improved extensibility (you can extend (i.e. subclass) the abstraction and implementation hierarchies independently),
    • hiding details from clients.  

    Bridge is a synonym for the “handle/body” idiom. This is a design mechanism that encapsulates an implementation class inside of an interface class. The former is the body, and the latter is the handle. The handle is viewed by the user as the actual class, but the work is done in the body. “The handle/body class idiom may be used to decompose a complex abstraction into smaller, more manageable classes. The idiom may reflect the sharing of a single resource by multiple classes that control access to it (e.g. reference counting).”

    Structure

    The Client doesn’t want to deal with platform-dependent details. The Bridge pattern encapsulates this complexity behind an abstraction “wrapper”.
    Bridge emphasizes identifying and decoupling “interface” abstraction from “implementation” abstraction.



    Example

    The Bridge pattern decouples an abstraction from its implementation, so that the two can vary independently. A household switch controlling lights, ceiling fans, etc. is an example of the Bridge. The purpose of the switch is to turn a device on or off. The actual switch can be implemented as a pull chain, simple two position switch, or a variety of dimmer switches.



    Check list
    • Decide if two orthogonal dimensions exist in the domain. These independent concepts could be: abstraction/platform, or domain/infrastructure, or front-end/back-end, or interface/implementation.
    • Design the separation of concerns: what does the client want, and what do the platforms provide.
    • Design a platform-oriented interface that is minimal, necessary, and sufficient. Its goal is to decouple the abstraction from the platform.
    • Define a derived class of that interface for each platform.
    • Create the abstraction base class that “has a” platform object and delegates the platform-oriented functionality to it.
    • Define specializations of the abstraction class if desired.

    Rules of thumb:
    • Adapter makes things work after they’re designed; Bridge makes them work before they are.
    • Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together.
    • State, Strategy, Bridge (and to some degree Adapter) have similar solution structures. They all share elements of the “handle/body” idiom. They differ in intent - that is, they solve different problems.
    • The structure of State and Bridge are identical (except that Bridge admits hierarchies of envelope classes, whereas State allows only one). The two patterns use the same structure to solve different problems: State allows an object’s behavior to change along with its state, while Bridge’s intent is to decouple an abstraction from its implementation so that the two can vary independently.
    • If interface classes delegate the creation of their implementation classes (instead of creating/coupling themselves directly), then the design usually uses the Abstract Factory pattern to create the implementation objects.
    Example Code

    Discussion. The motivation is to decouple the Time interface from the Time implementation, while still allowing the abstraction and the realization to each be modelled with their own inheritance hierarchy. The implementation classes below are straight-forward. The interface classes are a little more subtle. Routinely, a Bridge pattern interface hierarchy “hasa” implementation class. Here the interface base class “hasa” a pointer to the implementation base class, and each class in the interface hierarchy is responsible for populating the base class pointer with the correct concrete implementation class. Then all requests from the client are simply delegated by the interface class to the encapsulated implementation class.

    /*
     * Sample Code describing usage of bridge Design Pattern
     */

    #include <iostream>
    #include <iomanip.h>
    #include <string>

    using namespace std;

    class CTimeImp {
         public:
               CTimeImp(int hr, int min) {
                    m_nHr = hr;
                    m_nMin = min;
               }
               virtual void tell() {
                    cout << "time is " << m_nHr << m_nMin << endl;
               }
         protected:
               int m_nHr, m_nMin;
    };

    class CCivilianCTimeImp: public CTimeImp {
         public:
               CCivilianCTimeImp(int hr, int min, int pm): CTimeImp(hr, min) {
                    if (pm) {
                         strcpy(m_cWhichM, " PM");
                    }   
                    else {
                         strcpy(m_cWhichM, " AM");
                    }
               }
         /*
          * virtual
          */
               void tell() {
                    cout << "time is " << m_nHr << ":" << m_nMin << m_cWhichM << endl;
               }
         protected:
               char m_cWhichM[4];
    };

    class CZuluCTimeImp: public CTimeImp {
         public:
               CZuluCTimeImp(int hr, int min, int zone): CTimeImp(hr, min) {
                    if (zone == 5) {
                         strcpy(m_cZone, " Eastern Standard Time");
                    }
                    else if (zone == 6) {
                         strcpy(m_cZone, " Central Standard Time");
                    }
               }
               /*
                * virtual
                */
               void tell() {
                    cout << "time is " << m_nHr << m_nMin << m_cZone << endl;
               }
         protected:
               char m_cZone[30];
    };

    class CTime {
         public:
               CTime(){
              }
               CTime(int hr, int min) {
                    imp_ = new CTimeImp(hr, min);
               }
               virtual void tell() {
                    imp_->tell();
               }
         protected:
               CTimeImp *imp_;
    };

    class CCivilianTime: public CTime {
      public:
        CCivilianTime(int hr, int min, int pm) {
            imp_ = new CCivilianCTimeImp(hr, min, pm);
        }
    };

    class CZuluTime: public CTime {
         public:
               CZuluTime(int hr, int min, int zone) {
                    imp_ = new CZuluCTimeImp(hr, min, zone);
               }
    };

    int main() {    // main begins
         CTime *times[3];
         times[0] = new CTime(14, 30);
         times[1] = new CCivilianTime(2, 30, 1);
         times[2] = new CZuluTime(14, 30, 6);
         for (int i = 0; i < 3; i++) {
               times[i]->tell();
         }
         return 0;
    }    //main ends

    /*
    [sgupta@rhel55x86 bridge]$ ./bridge
    time is 1430
    time is 2:30 PM
    time is 1430 Central Standard Time
    [sgupta@rhel55x86 bridge]$
    */


    No comments:

    Post a Comment