Bridge design pattern in java

As stated by Gof:
“Decouple an abstraction from its implementation so that the two can vary independently”.When there are inheritance hierarchies in both interface and implementation then you loose coupling because of interdependence.In other words,Decoupling interface from implementation and hiding implementation detail of abstraction from client is main objectives of bridge design pattern.

Also known as:

Handle/Body

UML diagram of generic bridge design pattern:

Elements:

  • Abstraction
    • defines the abstraction’ s interface.
    • maintain reference to object of type implementor.
  • RefinedAbstraction
    • extends the interface defined by abstraction.
  • Implementor
    • 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 implementor interface provides only primitive operations,and abstraction defines higher-level operations based on these primitives.
  • ConcreteImplementor
    • implements the implementor interface and defines its concrete implementation.

When to use it:

  • Abstraction and implementation should be bound at compile time.
  • Both abstraction and implementation can have different hierarchies independently.You want to extend both hierarchies by subclassing.
  • Changes in implementation should have no impact on abstraction.
  • If you want to hide implementation of abstraction from client.
  • Best use when you have multiple implementation.

WorkFlow:

Abstaction forwards client request to its implementor object.

Example:

Before Applying bridge design pattern:
After applying bridge design pattern:
 

UML diagram for example:

Comparing to above generic description of bridge pattern.

My example includes following elements:
  • Shape(Abstraction)
  • Rectangle(RefinedAbstraction)
  • Circle(RefinedAbstraction)
  • Color(Implementor)
  • RedColor(ConcreteImplementor)
  • BlueColor(ConcreteImplementor)

 Java code for all above classes:

We have two inheritance hierarchies here.i.e Shape and Color.Now with help of bridge design pattern both can vary independently.
This is our abstraction class.
 Shape.java(Abstraction):

Rectangle.java(RefinedAbstraction):

Circle.java(RefinedAbstraction):


This is our implementor class.
Color.java(Implementor):

RedColor.java(ConcreteImplementor):

BlueColor.java(ConcreteImplementor):

BridgeDesignPatternMain.java:

 Output:

Related patterns:

An Abstract Factory can create and configure a particular bridge.

The Adapter design pattern convert interface of a class ito another interface clients expects.It is usually applied to system after they are designed.Bridge on other hand is used up-front in a design to let abstractions and implementation vary independently.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *