DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

JavaScript Design Patterns - Structural - Proxy

Image description

Proxy is a structural design pattern that lets us provide a substitute or placeholder for another object.

Imagine a scenario where we need to control access to an original object. This is where a proxy comes in. It acts as a gatekeeper, intercepting requests before they reach the original object. This interception allows us to perform additional actions, such as logging or caching, before the request is finally passed on to the original object.

Image description

A credit card is a proxy for a bank account, which is a proxy for a bundle of cash. Both implement the same interface: they can be used to make a payment.

In the below example, we are using this pattern to constrain the age of the pilots.

class Plane {
  fly() {
    return 'flying';
  }
}

class PilotProxy {
  constructor(pilot) {
    this.pilot = pilot;
  }

  fly() {
    return this.pilot.age < 18 ? `too young to fly` : new Plane().fly();
  }
}

class Pilot {
  constructor(age) {
    this.age = age;
  }
}
Enter fullscreen mode Exit fullscreen mode

👉 Use this pattern when an object is severely constrained and cannot live up to its responsibility.


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

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

Top comments (2)

Collapse
 
artydev profile image
artydev

Thank you

Collapse
 
jangelodev profile image
João Angelo

Hi Nhan Nguyen
Your tips are very useful
Thanks for sharing