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:

Please leave your appreciation by commenting on this post!

It takes just one minute and is worth it for your career.

Get started

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

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay