DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

JavaScript Design Patterns - Structural - Adapter

The adapter pattern allows classes to work together, creating a class interface into another one.

In this example, we use a SoldierAdapter to use the legacy method attack() in our current system and can support the new version of Soldiers SuperSoldiers.

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

  attack() {
    return this.level * 1;
  }
}

class SuperSoldier {
  constructor(level) {
    this.level = level;
  }

  attackWithShield() {
    return this.level * 10;
  }
}

class SoldierAdapter {
  constructor(superSoldier) {
    this.superSoldier = superSoldier;
  }

  attack() {
    return this.superSoldier.attackWithShield();
  }
}

export { Soldier, SuperSoldier, SoldierAdapter };
Enter fullscreen mode Exit fullscreen mode

🚀 Applicability:

➖ Use the Adapter class when we want to use some existing class, but its interface is not compatible with the rest of our code.

The Adapter pattern lets us create a middle-layer class that serves as a translator between our code and a legacy class, a 3rd-party class, or any other class with a weird interface.

➖ Use the pattern when we want to reuse several existing subclasses that lack some common functionality that can not be added to the superclass.

We could extend each subclass and put the missing functionality into new child classes. However, we will need to duplicate the code across all of these new classes, which smells really bad.


I hope you found it useful. Thanks for reading. 🙏

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

Feature flag article image

Create a feature flag in your IDE in 5 minutes with LaunchDarkly’s MCP server 🏁

How to create, evaluate, and modify flags from within your IDE or AI client using natural language with LaunchDarkly's new MCP server. Follow along with this tutorial for step by step instructions.

Read full post

Top comments (0)

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 practical breakdown on DEV’s open platform, where developers from every background come together to push boundaries. No matter your experience, your viewpoint enriches the conversation.

Dropping a simple “thank you” or question in the comments goes a long way in supporting authors—your feedback helps ideas evolve.

At DEV, shared discovery drives progress and builds lasting bonds. If this post resonated, a quick nod of appreciation can make all the difference.

Okay