Wonjoon Jang

Adapter pattern

Adapters are used to connect or let two different objects to associate with each other.

It’s sort of like a middle-device that makes it possible for the connection.

Likewise in Programming, let’s say we have Component A that returns an object with an XML format. We need this object’s data for Component B. But B requires datas to be in a JSON format. In this case, we can solve this problem by adding an Adapter also known as a Wrapper.

We could use this Apdapter to wrap the object and return the designated Object that meets qualifications.

class RoundHole {
  private radius: number;

  constructor(radius: number) {
    this.radius = radius;
  }

  getRadius() {
    return this.radius;
  }

  fits(peg: RoundPeg) {
    return this.getRadius() >= peg.getRadius();
  }
}

class RoundPeg {
  private radius: number;

  constructor(radius) {
    this.radius = radius;
  }

  getRadius() {
    return this.radius;
  }
}

class SquarePeg {
  private width: number;
  constructor(width: number) {
    this.width = width;
  }

  getWidth() {
    return this.width;
  }
}

class SquarePegAdapter extends RoundPeg {
  private peg: SquarePeg;

  constructor(peg: SquarePeg) {
    super((peg.getWidth() * Math.sqrt(2)) / 2);
    this.peg = peg;
  }

  getRadius() {
    return (this.peg.getWidth() * Math.sqrt(2)) / 2;
  }
}

const hole = new RoundHole(5);
const rpeg = new RoundPeg(5);

console.log(hole.fits(rpeg)); // true

const small_sqpeg = new SquarePeg(5);
const large_sqpeg = new SquarePeg(10);

// hole.fits(small_sqpeg);  => this doesn't work

const small_sqpeg_adapter = new SquarePegAdapter(small_sqpeg);
const large_sqpeg_adapter = new SquarePegAdapter(large_sqpeg);

console.log(hole.fits(small_sqpeg_adapter)); // true
console.log(hole.fits(large_sqpeg_adapter)); // false

This is how a Adapter pattern would look like if we’re using classes. However, if we’re using a functional programming pattern in Javascript. There’s no need to create a class like this. Since we are able to create objects easily with out a class in Javascript. We can just let a utility function named Adapter do this job.

It would be very helpful to use this pattern when there’s an existing class and the rest of the code doesn’t comply to it’s interface. We could use an Adapter class to let it’s return values to meet requirements.