Bridge Design Pattern Implementation

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

We are going to see yet another design pattern in this article. Bridge design pattern implementation is used with runtime binding of implementation is needed.

Bridge Design Pattern Implementation:

It is defined as

Bridge pattern decouples an abstraction from its implementation so that two can vary independently.

Generic Class Diagram:

Bridge Generic Class Diagram

Bridge Generic Class Diagram

Participants involved are:

  • Abstraction: Defines abstraction interface. Operations in it will be similar to that of operations in Implementor.
  • AbstractionImpl: Concrete Implementation of Abstraction. It HAS-A Implementor so that it can invoke its methods.
  • Implementor: This varies from Abstraction, methods will be similar to those defined in Abstraction.
  • ConcreteImplementor: Concrete implementation of Implementor

Bridge Design Pattern Implementation Example:

Consider our famous Java Persistence API framework and its implementations. JPA only specifies the contract to be fulfilled by its implementations. For this example we will take into consideration hibernate and eclipseLink. Let us design our classes as below

  • ORMFramework: Defines an interface which declares method required for saving an object. Corresponds to Abstraction.
  • ORMFrameworkImpl : Implements ORMFramework and it HAS-A JPA. Corresponds to AbstractionImpl.
  • JPA: Declares persist() operations, corresponds to Implementor.
  • Hibernate and EclipseLink both implement JPA. 

Let us write some code now.

ORMFramework.java

ORMFrameworkImpl.java

JPA.java

Hibernate.java

EclipseLink.java

Our bridge design pattern implementation is complete. Let us write code to test this now.

Note that,

  • we create different implementation object i.e. hibernate and jpa which both are JPA itself.
  • When we do new ORMFrameworkImpl(hibernate);, then we are actually bridging the Implementor and Abstraction. i.e. we are dynamically passing an implementation to abstraction. This is dynamic and hence not tightly coupled. This adheres to definition of bridge pattern.
  • Calling methods on ORMFramework invokes methods on Hibernate or EclipseLink implementation.

Output.

 

Example Class Diagram:

Bridge Patterh Example

Bridge Pattern Example

I hope this helped understand Bridge Design Pattern Implementation.

Share Button

Leave a Reply

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