DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

2

JavaScript Design Patterns - Structural - Bridge

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:

JavaScript-ready auth and billing that just works

JavaScript-ready auth and billing that just works

Stop building auth from scratch. Kinde handles authentication, user management, and billing so you can focus on what matters - shipping great products your users will love.

Get a free account

Top comments (2)

Collapse
 
artydev profile image
artydev

Thank you :-)

Collapse
 
nhannguyenuri profile image
Nhan Nguyen

You are welcome 😋

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Explore this compelling article, highly praised by the collaborative DEV Community. All developers, whether just starting out or already experienced, are invited to share insights and grow our collective expertise.

A quick “thank you” can lift someone’s spirits—drop your kudos in the comments!

On DEV, sharing experiences sparks innovation and strengthens our connections. If this post resonated with you, a brief note of appreciation goes a long way.

Get Started