Proxy Pattern

Introduction

A real world example can be a cheque or credit card is a proxy for what is in our bank account. It can be used in place of cash, and provides a means of accessing that cash when required. And that’s exactly what the proxy pattern does – “Controls and manage access to the object they are protecting”.

Another example in real life, when we want to book a flight, we sometimes will refer to a thrid party like Tripadvisor other than airline.
In this example, the Tripadvisor is a proxy. Using tripadvisor, we can avoid directly contacting with airline because tripadvisor can sell tickets on behalf of airline. However, different from airline, Tripadvisor may also provide some other service that airline doesn’t have such as hotel coupon.

Code Example

UserService.java:

1
2
3
4
5
6
7
8
package com.xliu.demo02;

public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}

Define a interface that include several database operations.

UserServiceImpl.java:

1
2
3
4
5
6
7
8
9
10
11
package com.xliu.demo02;

public class UserServiceImpl implements UserService {
public void add() { System.out.println("Add a user"); }

public void delete() { System.out.println("Delete a user"); }

public void update() { System.out.println("Update a user"); }

public void query() { System.out.println("Query a user"); }
}

Implement the interface.

UserServiceProxy.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.xliu.demo02;

public class UserService Proxy implements UserService {
UserImpl user = new UserImpl();
public void add() {
log("add");
user.add();
}

public void delete() {
log("delete");
user.delete();
}

public void update() {
log("update");
user.update();
}

public void query() {
log("query");
user.query();
}

public void log(String msg){
System.out.println("Use" +msg+ "method");
}
}

Design a proxy.

Client:

1
2
3
4
5
6
public class Client {
public static void main(String[] args) {
Proxy proxy = new Proxy();
proxy.add();
}
}

Using the add() method at Client without interacting with UserServiceImpl but Proxy

Note

Using compositing to call a object of User.

Those methods need to be rewrite in proxy class but using the User object to call instead of repeating the same method body.

In this example I showed that a proxy can not only provide an interface of original method to client, but also do some modification (like adding a log in this example).

Advantage

  • One of the advantages of Proxy pattern is security.
  • This pattern avoids duplication of objects which might be huge size and memory intensive. This in turn increases the performance of the application.

Disadvantage

This pattern introduces another layer of abstraction which sometimes may be an issue if the RealSubject code is accessed by some of the clients directly and some of them might access the Proxy classes. This might cause disparate behaviour.