DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

2

JavaScript Design Patterns - Structural - Bridge

Image description

The bridge pattern allows one interface in our class to build different implementations depending on what instance we are receiving and what instance we need to return.

In the example below, we create a bridge between types of Soldiers and types of Weapons. In this way, we can correctly pass the instance of weapons to our soldiers.

class Soldier {
  constructor(weapon) {
    this.weapon = weapon;
  }
}

class SuperSoldier extends Soldier {
  constructor(weapon) {
    super(weapon);
  }

  attack() {
    return 'SuperSoldier, Weapon: ' + this.weapon.get();
  }
}

class IronMan extends Soldier {
  constructor(weapon) {
    super(weapon);
  }

  attack() {
    return 'Ironman, Weapon: ' + this.weapon.get();
  }
}

class Weapon {
  constructor(type) {
    this.type = type;
  }

  get() {
    return this.type;
  }
}

class Shield extends Weapon {
  constructor() {
    super('shield');
  }
}

class Rocket extends Weapon {
  constructor() {
    super('rocket');
  }
}

export { SuperSoldier, IronMan, Shield, Rocket };
Enter fullscreen mode Exit fullscreen mode

๐Ÿ‘‰ Use this pattern when we need to use a specific implementation in runtime from an abstraction.

๐Ÿš€ A complete example here: https://stackblitz.com/edit/vitejs-vite-efyrjy?file=main.js


I hope you found it useful. Thanks for reading. ๐Ÿ™

Let's get connected! You can find me on:

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (2)

Collapse
 
artydev profile image
artydev โ€ข

Thank you :-)

Collapse
 
nhannguyendevjs profile image
Nhan Nguyen โ€ข

You are welcome ๐Ÿ˜‹

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more