This article describes the proxy design pattern in java.
Proxy Design Pattern is a basic plan design among the Gang Of Four(GOF) Design Patterns. An auxiliary structure design manages how the connections between objects are acknowledged to improve the plan.
How the proxy design pattern works?
Proxy pattern provides a surrogate or placeholder for another object to control access to it. In computer programming, the proxy design is a product configuration design. A proxy, in its most broad structure, is a class working as an interface to something different.
The proxy could interface to anything: a system association, a vast object in memory, a record, or some other asset that is costly or difficult to copy. To put it plainly, a proxy is a wrapper or operator object that is being called by the customer to get to the genuine serving object in the background. Utilisation of the intermediary can basically be sent to the genuine item or can give extra rationale. In the proxy, additional users can be given, for instance, reserving when activities on the genuine item are asset serious, or checking preconditions before tasks on the genuine object is conjured.
For the customer, use of a proxy object is like utilising the genuine item, on the grounds that both actualise a similar interface.
Implementation of proxy design pattern in real-life scenario
We can make an Image
interface and solid classes executing the Image
interface. ProxyImage
is a proxy class to lessen memory impression of RealImage
object stacking.
Proxy Design Pattern Example in Java
Create an interface
Image.java
public interface Image { void display(); }
Create concrete classes implementing the same interface.
RealImage.java
public class RealImage implements Image { private String fileName; public RealImage(String fileName){ this.fileName = fileName; loadFromDisk(fileName); } @Override public void display() { System.out.println("Displaying " + fileName); } private void loadFromDisk(String fileName){ System.out.println("Loading " + fileName); } }
ProxyImage.java
public class ProxyImage implements Image{ private RealImage realImage; private String fileName; public ProxyImage(String fileName){ this.fileName = fileName; } @Override public void display() { if(realImage == null){ realImage = new RealImage(fileName); } realImage.display(); } }
Use the ProxyImage
to get the object of RealImage
class when required.
ProxyPatternDemo.java
public class ProxyPatternDemo { public static void main(String[] args) { Image image = new ProxyImage("test_10mb.jpg"); //image will be loaded from disk image.display(); System.out.println(); //image will not be loaded from disk image.display(); } }
Verify the output.
Loading test_10mb.jpg Displaying test_10mb.jpg Displaying test_10mb.jpg