Bridge

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

Design Patterns: Elements of Reusable Object-Oriented Software

The Bridge pattern is a bit mysterious for me, I’m trying to find a concrete implementation of it in the .NET Framework, but it is a bit hard task. The main point in bridge is to decouple the implementation from its abstraction, and let them evolve separately. We have four key players here:

  • Abstraction: is the interface our client is aware of. It also maintains a reference on the implementation (something moved into the RefinedAbstraction commonly).
  • RefinedAbstraction: implements Abstraction, and extends its functionality (in all examples, the reference to Implementor was moved here).
  • Implementor: defines the functionality of abstraction, and the methods to call.
  • ConcreteImplementor: extends implementor.

Now let’s see a real example:

//Abstraction
interface IShape
{
                public void Draw();
}
//Implementor
interface  IDrawingApi
{
                public void DrawRectangle(Point x, Point y);
}
//ConcreteImplementor
class RectangleDrawer :IDrawingApi
{
                public void DrawRectangle(Point x, Point y)
                {
                Console.WriteLine(“Rectanlge drawn between {0} and {1}”, x, y);
                }
}
//RefinedAbstraction
class Rectanlge: IShape
{
                Point x;
                Point y;
                private IDrawingApi drawing;
                public  Rectanlge(Point x, Point y, IDrawingApi api)
                {
                this.x=x;
                this.y =y;
drawing = api;
}
public void Draw()
{
drawing.DrawRectangle(x, y);
                }
}

OK, maybe not  the most clever example on the Internet, but the main idea can be followed. We have two interfaces, Abstraction, which defines what our class is capable of, and Implementor, which tells us how it is done. Notice that the client is only aware of the existence of Abstraction, and uses it to work. The implementation then can vary independently from abstraction, which is a very good thing in dynamically changing systems.

Further Readings:

Bridge pattern on Wikipedia

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: