The Proxy pattern is a structural design pattern that provides a surrogate or placeholder object to control the access to another object. It acts as an intermediary between the client and the actual object and allows for additional functionality to be added around the objects core functionality. The Proxy pattern is commonly used to implement security checks, caching, lazy initialization, or remote communication. Here is an example of implementing the Proxy pattern in Java:
The Image interface represents the subject interface, which declares the display() method that clients will invoke.
The RealImage class is the real subject that performs the core functionality of loading and displaying an image. It implements the Image interface.
The ImageProxy class is the proxy class that acts as an intermediary between the client and the real image. It also implements the Image interface and maintains a reference to the real image.
In the ImageProxy class, the display() method checks if the real image has been loaded. If not, it creates an instance of the RealImage class and delegates the display() call to the real image.
The client code in the Client class demonstrates the usage of the proxy. It creates instances of the proxy (ImageProxy) and calls their display() methods. The first call triggers the loading and display of the actual image, while subsequent calls use the already loaded image.
By using the Proxy pattern, you can control access to an object and add additional functionality around its core operations. The proxy can handle tasks such as lazy initialization, caching, logging, or security checks, without the client being aware of it. This pattern provides a way to achieve transparent or on-demand access to the real object and enables you to control or enhance the behavior of the real object as needed.