Contact Me

Bridge

 It is a structural design pattern that allows you to decouple an abstraction from its implementation so that the two can vary independently


Here is an example of the bridge pattern in JavaScript:


// The abstraction class

class Abstraction {

constructor(implementation) {

  this.implementation = implementation;

}

operation() {

  console.log('Abstraction: Delegating operation to implementation.');

  return this.implementation.operation();

}

}

// The implementation base class

class Implementation {

operation() {

  throw new Error('Not implemented');

}

}

// A concrete implementation

class ConcreteImplementationA extends Implementation {

operation() {

  console.log('ConcreteImplementationA: Performing operation.');

}

}

// Another concrete implementation

class ConcreteImplementationB extends Implementation {

operation() {

  console.log('ConcreteImplementationB: Performing operation.');

}

}

// Client code

const abstraction = new Abstraction(new ConcreteImplementationA());

abstraction.operation();

const anotherAbstraction = new Abstraction(new ConcreteImplementationB());

anotherAbstraction.operation();


In this example, the Abstraction class represents an abstract interface that defines a method, operation(). The Implementation base class defines the interface for concrete implementation classes, but it doesn't provide a concrete implementation of the operation() method. The ConcreteImplementationA and ConcreteImplementationB classes are concrete implementations of the operation() method.

The Abstraction class holds a reference to an instance of the Implementation interface. The operation() method of the Abstraction class delegates to the operation() method of the implementation instance.

The client code can work with the Abstraction interface, creating instances of the Abstraction class and passing different implementations to them. The client doesn't need to know about the concrete implementation classes; it only needs to know about the Abstraction interface. This decouples the client code from the implementation and allows the two to vary independently.