Published on

[Structural] Adapter

Authors
  • avatar
    Name
    Khánh
    Twitter

Problems

  • How to use an old layer code for a new layer without effect to the old code?

Adapter pattern

  • Create an adapter to connect an old layer to use in the new context.

Steps:

  • Determine an old layer
  • Create a new layer with input is an old instance
  • Using the new layer in new context.

Example:

  1. Old layer
class OldSystem {
  oldRequest() {
    return "Old system request";
  }
}
  1. New layer
interface Target {
  request(): string;
}

class SystemAdapter implements Target {
  constructor(private oldSystem: OldSystem) {}
  request(): string {
    return this.oldSystem.oldRequest();
  }
}
  1. Implementation of the new layer
const oldSystem = new OldSystem();
console.log(oldSystem.oldRequest()); // Old system request

const newSystem = new SystemAdapter(oldSystem);
console.log(newSystem.request()); // Old system request

Conclusions

  • Keep the old layer (no need to modify it)
  • Easier to expand the old layer
  • Can reuse code