The Proxy Pattern in Java

Introduction to the Proxy Pattern

Design pattern in a simple meaning, is a way to design reusable object-oriented code. We can think of ways to design our classes, interfaces, enums and their members so that the code is reusable but flexible.

There are 23 most important design patterns, pioneered by the book Design Patterns: Elements of Reusable Object-Oriented Software, written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides or Gang of Four for short. We will cover these design pattern one by one.

The Proxy pattern provides a representative object that controls access to another object.

Implementation of Proxy Pattern in Java

For example, in src folder we define a File interface:

public interface File {
  void readFile();
}

Nothing special here, next we create a MyFile class that implements the File interface:

public class MyFile implements File{
  public void readFile() {
    System.out.println("Reading MyFile");
  }
}

Next, we can use the Proxy pattern to control access to MyFile. For example only some users can access MyFile. We define the User class:

public class User {
  private String name;
  public User(String name) {
    this.name = name;
  }
  public String getName() {
    return name;
  }
}

Now we create a proxy, the MyFileProxy class. The proxy will only allow “admin” user to access MyFile:

public class MyFileProxy implements File{
  private final User user;
  private final File file;
  public MyFileProxy(User user, File file) {
    this.user = user;
    this.file = file;
  }
  public void readFile() {
    if ("admin".equals(user.getName())){
      file.readFile();
    }
    else {
      System.out.println("You do not have permission");
    }
  }
}

And in Test.java:

public class Test{
  public static void main(String... args){
    MyFile myFile = new MyFile();
    User admin = new User("admin");
    User user = new User("user");
    var proxy1 = new MyFileProxy(admin, myFile);
    var proxy2 = new MyFileProxy(user, myFile);
    proxy1.readFile();
    proxy2.readFile();
  }
}

Now run Test.java and we can see that “admin” can call MyFile readFile() method but “user” can not:

Reading MyFile
You do not have permission

Leave a Reply