GoF Proxy Pattern

Attach additional responsibilities to an object dynamically. Proxys provide a flexible alternative to subclassing for extending functionality.

Componentized Proxy Pattern

PerfectJPattern's offers a componentized version of the Proxy pattern. In order to implement proxies and take advantage of PerfectJPattern's implementation, users are required to extend AbstractProxy and optionally override the invokeUnderlying method. The invokeUnderlying will intercept all method calls on the real Subject instance. See example below or checkout the SynchronizedProxy.java implementation that will protect any Subject type from race-conditions. This implementation would replace the need for e.g. Collections.synchronizedCollection(...), Collections.synchronizedSet(...), Collections.synchronizedList(...), etc. See example under TestAsynchronousSubject.java

Implementing proxies using PerfectJPattern's AbstractProxy offers the following advantages:

  • Proxy identity i.e. equals is automatically handled to match that of the Subject, thus to the outside world the Proxy still is the Subject assuming equals defines identity
  • Automatic proxying: proxying interfaces with large number of features in a snap. Those Subject methods not defined by the Proxy will be automatically forwarded to the Subject so you don't have to. Users are only required to provide implementation for those proxied methods minimally.
  • Maintainability: the Subject interface may change but the Proxies will be minimally or not impacted at all. In the traditional manual implementation, once the Subject interface changed, all Proxies also had to be changed posing a high toll in maintainability.


UML Class Design



Example