DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

3

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:

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

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