/ JavaScript

Bridge Design Pattern In JavaScript

Definition

The Bridge design pattern, also known as the double Adapter pattern, is a structural design pattern that decouples an abstraction from its implementation so that the two can vary independently. It facilitates very loose coupling of objects and allows two components to work together with each component having its own interface.

Bridge pattern is about preferring composition over inheritance. Implementation details are pushed from a hierarchy to another object with a separate hierarchy.

Use Cases

  • We want run-time binding of the implementation.
  • We have a proliferation of classes resulting from a coupled interface and numerous implementations.
  • We want to share an implementation among multiple objects.
  • We need to map orthogonal class hierarchies.

Example

One of the abstract examples is shown in the following picture which shows the design before applying the pattern.

without-the-bridge

We had to create a colored component of each of the shapes that we have, which is of course inefficient. Let's see how we can improve it by applying the Bridge pattern.

with-bridge

Better have the code speak.

function Circle(color) {
    this.color = color;

    this.toString = function () {
        return `${this.color.getColorName()} Circle`;
    };
}

function Rectangle(color) {
    this.color = color;

    this.toString = function () {
        return `${this.color.getColorName()} Rectangle`;
    };
}

function Triangle(color) {
    this.color = color;

    this.toString = function () {
        return `${this.color.getColorName()} Triangle`;
    };
}

function Red() {
    this.getColorName = function () {
        return 'Red';
    }
}

function Blue() {
    this.getColorName = function () {
        return 'Blue';
    }
}

function Green() {
    this.getColorName = function () {
        return 'Green';
    }
}

const redColor = new Red();
const blueColor = new Blue();
const greenColor = new Green();

const redCircle = new Circle(redColor);
const blueCircle = new Circle(blueColor);
const greenRectangle = new Rectangle(greenColor);

console.log(redCircle.toString());
console.log(blueCircle.toString());
console.log(greenRectangle.toString());
Anas Shekhamis

Anas Shekhamis

A software engineer who specializes in architecting and developing web applications. On a daily basis, I use Python, JavaScript, Ruby, and PHP to design and implement API's and build web applications.

Read More
Bridge Design Pattern In JavaScript
Share this