Bridge Pattern in Java

A system generally has two sections to it. One is the abstracted class that contains all of the complex codes. libraries and databases. This class (or group of classes) forms the basic framework of the application and the services it has to offer. Together, this is called the implementation. The other part of any system is called the Abstraction. This is that part of an application that a client code can access. It acts as an outer interface that envelopes the implementation inside. Clients are only concerned with the Abstraction. The bridge pattern acts as a bridge between the two connecting the Abstraction with the Implementation while allowing both parts to act independently.

Definition

As defined by the Gang of Four, Bridge Pattern is used to ‘decouple an abstraction from its implementation such that both parts can be developed independently’. In simpler terms, the bridge pattern breaks down huge complex classes into smaller classes and subclasses that abstract the main class. This pattern particularly helps in error-solving as looking for errors in a small class is much easier as compared to a complex interface.

Example and Code

This example will deal with two layers of abstraction where a primary car class will be abstracted by a model.

//this is the basic interface

public interface Car {
String paint ();

// We will paint the car red. The class below will implement the Car interface

public class Red implements Car {
@override
public String paint() {
return “The car has been painted red”;
}
}

//This class will determine the company and refer to the car object (will act as a bridge between the two classes).

public abstract class Toyota {
public Car car;
abstract public String manufactur();
}

//Finally this class will deal with the model of the car that you want painted.

public class Prius extends Toyota {
public Prius (Car car) {
super (car); }
@override
public void paint() {
System.out.println (Prius has been coloured + car.paint());
}
}

 

When Should the Bridge Pattern be used?

The Bridge design pattern in JAVA should be used whenever you have a class in hand that is quite lengthy as well as complex to break it down into subclasses. The pattern thereafter will help you work out class hierarchies and make bridges between them.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.