1. Introduction
In real life, let's assume that you are a movie director. If you want to ask Jackie Chen to act in your new film "Rookie Blue", you would not directly meet Jackie but his agent first. How much you need to pay Jackie before he comes and after the film ends are all discussed with Jackie's agent, while Jackie is only focusing on playing in the movie.
In programming, we usually have the same logic as we need to create a proxy class to do extra work for our object. Clients can only access the proxy instead of the target object directly. We called it the "Proxy Pattern" in Java Programming. Here let's try to achieve our example using Java.
2. Static Proxy Pattern
First, we need to create the interface of the moive star; This class has only one method.
public interface MovieStar {
public void act(String movie);
}
Then, we created a new class called Jackie to implement our interface;
public class Jackie implements MovieStar{
@Override
public void act(String movie) {
System.out.println("Act in movie"+movie);
}
}
The next step is to construct the agent class:
public class MovieAgent implements MovieStar{
//target object using injection
private MovieStar star;
public MovieAgent(MovieStar star){
this.star = star;
}
public void prePaid(){
System.out.println("Pre-Paid $500000 before filming");
}
public void remindPaid(){
System.out.println("Pay $6000000 after filming");
}
@Override
public void act(String movie) {
prePaid();
star.act("Rookie Chen");
remindPaid();
}
}
Here, we will inject our target object into the proxy class. So, from the outside, clients will only have access to the agent class while the real star play is Jackie himself. Another functions the agent play is receiving money before and after the movie. Finally, we will achieve this in our test class.
public class Main {
public static void main(String[] args) {
MovieAgent agent = new MovieAgent(new Jackie());
agent.act("Rookie Blue");
}
}
This is the result:
Pre-Paid $500000 before filming
Act in movieRookie Blue
Pay $6000000 after filming
Conclusion
This is what we called "Proxy Pattern" design. The core concept of proxy pattern is using a proxy class to "wrap" our target object to perform extra functions or methods. What we showed here is called the "Static Proxy Pattern" the disadvantage of the static proxy pattern is we need to create a unique proxy class for every target object. To make our proxy pattern easier, we have another method called "Dynamic Proxy Pattern", which I will discuss in my following tutorial.