Proxy
The Proxy design pattern is used to provide a stand-in for a real class. The proxy implements the same interface as the real class and forwards method calls to it.
Contents |
Use When
The GoF specify four situations in which Proxy is applicable:
- A remote proxy can be used to represent an object which is not contained in the application. For example, an object that is on another networked computer.
- A virtual proxy is used to implement lazy initialization. Useful for creating expensive objects when needed rather than at startup.
- A protection proxy is used to have greater control over the access rights to the object.
- A smart reference can use a proxy so that when the real object is accessed it can perform additional actions such as creating it on first access and counting references so that it can be deleted when it is no longer referenced (not obvious that this would be important in languages with garbage collection, but there might be additional actions that need to be performed on deletion).
Structure
Diagram from the GoF:
Participants
Proxy
The Proxy has a reference to the Real Subject so that it can access it. It also provides an interface for clients that is identical to that of the subject it is protecting so that it can be used instead of its subject. Apart from controlling access to the subject, it may also be responsible to create and delete it.
Specific proxies may have additional responsibilities. A protection proxy for example also has to check that the caller has permission to perform the operation n question. A virtual proxy may cache information about the real subject so that it does not have to access the subject for every request. A remote proxy has to encode the request before passing it on to the real subject in a different address space.
Subject
The Subject defines the interface of the Proxy and the object it is protecting so that the Proxy can be used where the Subject is expected.
Real Subject
The Real Subject defines the real object that is protected by the Proxy.
Consquences
The proxy design pattern introduces a level of indirection to an object. This has many uses for performance optimization as well as greater flexibility on how references are kept and what kind of objects these references can be made to.
See Also
Design patterns | |
---|---|
Creational: Abstract Factory | Builder | Factory Method | Prototype | Singleton |