DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

JavaScript Design Patterns - Structural - Adapter

Image description

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:

Image of Docusign

๐Ÿ› ๏ธ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

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

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Communityโ€”every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple โ€œthank youโ€ goes a long wayโ€”express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay