Applied Design Patterns with Java
Structural :: Proxy (207) {C ch 15}
Applicability
The Proxy is applicable whenever there is a need for a more versatile or sophisticated
reference to an object than a simple pointer. Here are several situations in which the Proxy pattern is applicable:
- A remote Proxy provides a local representative for an object in a different
address space;
- A virtual Proxy creates expensive objects on demand. The ImageProxy described
in the Motivation is an example of such a proxy;
- A protection Proxy controls access
to the original object. Protection proxies are useful when objects should have different access rights;
- A smart
reference is a replacement for a bare pointer
that performs additional actions when an object is accessed. Typical
uses include: counting the number of references to the real object so that it can be freed automatically when
there are no more references (also called smart
pointers); loading a persistent object into
memory when it's first referenced; and checking that the real object is locked before it's accessed to ensure that
no other object can change it.
Structure
The Proxy pattern has this general organization:
Here's a possible object diagram of a Proxy structure at run-time:
Participants
- Proxy (ImageProxy)
maintains a reference that lets the Proxy access the real subject. Proxy may refer to a Subject
if the RealSubject and Subject interfaces are the same; provides an interface identical to Subject's so that a
Proxy
can by substituted for the real subject; controls access to the real subject and may be responsible for creating
and deleting it. Other responsibilities depend on
the kind of Proxy:
- remote proxies are responsible for encoding a request and its arguments and for sending the encoded request
to the real subject in a different address space;
- virtual proxies
may cache additional information about the real subject so that they can postpone accessing it. For example, the
ImageProxy from the Motivation caches the real image's extent;
- protection proxies
check that the caller has the access permissions required to perform a request.
- Subject (Graphic) defines the common interface for RealSubject and Proxy
so that a Proxy can be used anywhere a RealSubject is expected.
- RealSubject (Image) defines the real object that the Proxy represents.
Catalog Structural Prev Next