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:

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

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

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. ❤️