Design Patterns in Action(7)- Proxy

A series of programming design patterns illustration with examples with JavaScript/Python

Photo by Alexa Soh on Unsplash

Simply put, the Proxy pattern is a way to avoid direct access to an object through a substitute, aka. Proxy. The proxy object looks like the same to the client as the real subject, so they will need to have the same interface. Requests from the client are passed to the real subject through the proxy, with a bit added flavour, e.g. caching, logging, encryption, etc. So in a way, it’s a bit like a middleware.

The participants in Proxy pattern:

  • Real Subject: object that the client really want.
  • Proxy Subject: a proxy that implements all real subject’s interface but does something extra without the client realising that.

The implementation of Proxy pattern is pretty simple, however, there’s another native implementation in JavaScript that encapsulates the pattern with an abstract API — feel free to take a look.

So, ours example will implement Proxy for the purpose of caching. Let’s take a look at python one. Note the real object fetches the bread label asynchronously so the proxy will cache the response to accelerate the speed to return the response to the client.

This is another with JavaScript:

That’s so much of it! Happy Reading!