Using Proxy Pattern in Java
This particular design pattern is design to solve three common problems that programmers have:
- The connection with an object can’t be interpreted with a pointer.
- Access operations are complex
- Only a subset of access opportunities should be allowed
In order to implement it, we will need to divide our class / object in two. I will demonstrate how to implement the proxy pattern by writing a simple File class.
Step 1: Create an Interface or Abstract Class
Create an interface/class with all the general properties.
public interface File {
public void save();
public void open();
public void write();
}Step 2: Create the original class
Now it is time to write our regular class as it was original intended.
public class RealFile implements File { private String fileName; public RealFile(String fileName) {
this.fileName = fileName;
} public void save() {
System.out.println(“SAVING: “ + fileName);
}public void open() {Get Pablo Osinaga’s stories in your inbox
Join Medium for free to get updates from this writer.
System.out.println(“OPENING: “ + fileName);
} public void write() {
System.out.println(“WRITING: “ + fileName);
}}
Step 3: Create the proxy class
This class should have an instance of the original class as an attribute and only the from the interface or superclass inherited methods. All of these methods must verify if the above mencionated attributed has already a value. In case it hasn’t it should assign a new value to it. After that we need to call the same method from the original class.
public class ProxyFile implements File{ private RealFile realFile;
private String fileName; public ProxyFile(String fileName) {
this.fileName = fileName;
} public void save() {
if(realFile == null){
realFile = new RealFile(fileName);
}
realFile.save();
} public void open() {
if(realFile == null){
realFile = new RealFile(fileName);
}
realFile.open();
} public void write() {
if(realFile == null){
realFile = new RealFile(fileName);
}
realFile.write();
}}
Step 4: Use it!
In order to test our work. We need to initialise an instance of our interface / abstract class with a new proxy class. After that we can call it’s method as many times as we want.
File proxyFile= new ProxyFile(“test.txt”);proxyFile.open();
proxyFile.write();
proxyFile.save();
proxyFile.write();
proxyFile.save();
You can get the example code from my GitHub account: https://github.com/paguos/designpatterns










