Applied Design Patterns with Java

Structural :: Proxy (207) {C ch 15}


Collaborations

Consequences

The Proxy pattern introduces a level of indirection when accessing an object. The additional indirection has many uses, depending on the kind of Proxy:

  1. A remote Proxy can hide the fact that an object resides in a different address space.
  2. A virtual Proxy can perform optimizations such as creating an object on demand.
  3. Both protection Proxies and smart references allow additional housekeeping tasks when an object is accessed.

There's another optimization that the Proxy pattern can hide from the client, called Copy-on-Write, and it's related to creation on demand. Copying a large and complicated object can be an expensive operation. If the copy is never modified, then there's no need to incur this cost. By using a Proxy to postpone the copying process, this delays paying the price of copying the object until it's modified. To make Copy-on-Write work, the subject must be reference counted. Copying the Proxy will do nothing more than increment this reference count. Only when the client requests an operation that modifies the subject does the Proxy actually copy it. In that case the Proxy must also decrement the subject's reference count. When the reference count goes to zero, the subject gets deleted. Copy-on-Write can reduce the cost of copying heavyweight subjects significantly.

Catalog Structural Prev Next