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.
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;
}
}
๐ 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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Top comments (2)
Thank you
Hi Nhan Nguyen
Your tips are very useful
Thanks for sharing