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:

Image of Timescale

Timescale ā€“ the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (2)

Collapse
 
artydev profile image
artydev ā€¢

Thank you :-)

Collapse
 
nhannguyendevjs profile image
Nhan Nguyen ā€¢

You are welcome šŸ˜‹

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

šŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay