Bridge Pattern

What is Bridge Design Pattern ?

Bridge design pattern is used to decouple a class into two parts — abstraction and it’s implementation — so that both can evolve in future without affecting each other. It increases the loose coupling between class abstraction and it’s implementation.

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

The Bridge Pattern is also known as Handle or Body.

Advantage of Bridge Pattern

  • It enables the separation of implementation from the interface.
  • It improves the extensibility.
  • It allows the hiding of implementation details from the client.

Usage of Bridge Pattern

  • When you don’t want a permanent binding between the functional abstraction and its implementation.
  • When both the functional abstraction and its implementation need to extended using sub-classes.
  • It is mostly used in those places where changes are made in the implementation does not affect the client

UML Diagram for Bridge Pattern

bridge_pattern

Following participants constitute the bridge design pattern.

  • Abstraction (abstract class):It defined the abstract interface i.e. behavior part. It also maintains the Implementer reference.
  • RefinedAbstraction (normal class):It extends the interface defined by Abstraction.
  • Implementer (interface):It defines the interface for implementation classes. This interface does not need to correspond directly to abstraction interface and can be very different. Abstraction imp provides an implementation in terms of operations provided by Implementer interface.
  • ConcreteImplementor (normal class):It implements the Implementer interface.

Implementation:

Now let see the implementation with common example having Color as interface and  Shape as abstract class.

Color.java

Shape.java

Triangle and Pentagon implementation classes of Shape as below.

Triangle.java

 

Pentagon.java

RedColor and BlueColor are the implementing class for Color interface

RedColor.java

 

BlueColor.java

Lets test our bridge pattern implementation with a test program.

BridgePatternTest.java

Output of above class is:

Triangle filled with color red.

Pentagon filled with color blue.

Bridge design pattern can be used when both abstraction and implementation can have different hierarchies independently and we want to hide the implementation from the client application.

   

Comments are closed