Proxy is a struc­tur­al design pat­tern that lets you pro­vide a sub­sti­tute or place­hold­er for anoth­er object. A proxy con­trols access to the orig­i­nal object, allow­ing you to per­form some­thing either before or after the request gets through to the orig­i­nal object.

Problem #1: the object is complex, its instantiation is expensive

Solution #1:

Problem #2: the object is located on another node (i.e. on a web server), accessing the object is expensive

Solution #2:

image.png

image.png

Structure

image.png

  1. The Ser­vice Inter­face declares the inter­face of the Ser­vice. The proxy must fol­low this inter­face to be able to dis­guise itself as a ser­vice object.
  2. The Ser­vice is a class that pro­vides some use­ful busi­ness logic.
  3. The Proxy class has a ref­er­ence field that points to a ser­vice object. After the proxy fin­ish­es its pro­cess­ing (e.g., lazy ini­tial­iza­tion, log­ging, access con­trol, caching, etc.), it pass­es the request to the ser­vice object. Usu­al­ly, prox­ies man­age the full life­cy­cle of their ser­vice objects.
  4. The Client should work with both ser­vices and prox­ies via the same inter­face. This way you can pass a proxy into any code that expects a ser­vice object.”

<aside>

Applicability

<aside>

How to Implement

  1. If there’s no pre-exist­ing ser­vice inter­face, cre­ate one to make proxy and ser­vice objects inter­change­able. Extract­ing the inter­face from the ser­vice class isn’t always pos­si­ble, because you’d need to change all of the ser­vice’s clients to use that inter­face. Plan B is to make the proxy a sub­class of the ser­vice class, and this way it’ll inher­it the inter­face of the service.
  2. Cre­ate the proxy class. It should have a field for stor­ing a ref­er­ence to the ser­vice. Usu­al­ly, prox­ies cre­ate and man­age the whole life cycle of their ser­vices. On rare occa­sions, a ser­vice is passed to the proxy via a con­struc­tor by the client.
  3. Imple­ment the proxy meth­ods accord­ing to their pur­pos­es. In most cases, after doing some work, the proxy should del­e­gate the work to the ser­vice object.
  4. Con­sid­er intro­duc­ing a cre­ation method that decides whether the client gets a proxy or a real ser­vice. This can be a sim­ple sta­t­ic method in the proxy class or a full-blown fac­to­ry method.
  5. Con­sid­er imple­ment­ing lazy ini­tial­iza­tion for the ser­vice object.” </aside>