DEV Community

jzfrank
jzfrank

Posted on

HFDP(11) - Proxy Pattern

Proxy manages and controls access. Proxy is a stand in for a real object. Proxy pattern has a lot of variations.

For example, if we want to call a method of an object living remotely in another JVM, we need to make use of the Remote Proxy. In java, we could achieve this by using rmi technology. Basically, the client calls a stub that implements the same Remote interface as the real subject. The stub then forwards the request to the skeleton living in the JVM, which then calls the real subject and forwards back returned value. Through the time, the client thinks it is accessing the real subject, which it is not doing this directly.

Remote Proxy

Another well-known example is the Virtual Proxy. It is used for wrapping an expensive object like an image fetched from a network. Let's say you want to display an image on screen. Instead of fetching the image and manages the waiting yourself, you could delegate the task to a virtual proxy. It will fire a thread to fetch the image, and renders waiting texts while waiting. In this manner, you reduced the coupling in code.

Virtual Proxy

We may also need to manage access, which brings the Protection Proxy. It wraps an object and decides if the client could access certain methods of it. In Java it is implemented via reflection. e.g.

Person getOwnerProxy(Person, person) {
  return (Person) Proxy.newProxyInstance(
    person.getClass().getClassLoader(),
    person.getClass().getInterfaces(),
    new OwnerIncovationHandler(person));
}
Enter fullscreen mode Exit fullscreen mode

where OwnerIncovationHandler implements InvocationHandler. Its method signature is Object invoke(Object proxy, Method method, Object[] args).

We've seen a number of patterns that serve as wrapper. They look similar but serves different purposes:

  • Decorator Pattern: wrap an object add behaviors
  • Facade Pattern: wrap possible many objects and simplify interfaces
  • Adapter Pattern: wraps an object and implements another interface
  • Proxy Pattern: wraps an object and controls access.

Proxy pattern has many variations:

  • Firewall Proxy (control access to network recourses) -> e.g. corporate firewall system.
  • Smart Reference Proxy (provide additional actions when a subject is referenced e.g. count)
  • Caching Proxy (temp store expensive resources) -> web server proxies and content management and publishing systems.
  • Synchronization Proxy (provides safe access to a subject from multiple threads)
  • Complexity Hiding Proxy (pretty much like Facade)
  • Copy-on-Write Proxy (lazy copying, variant of Virtual Proxy)

Top comments (0)