What is Proxy Pattern?
Proxy pattern is a structural pattern that provides a surrogate or placeholder for another object to control access to it.
When to use it?
There are different types of proxies depending on its specific purpose. But essentially, Proxy pattern is providing a representative for another object.
Use the virtual proxy when the creation of a resource is expensive, and you want to delay its instantiation until it is actually needed.
Use the protection proxy when you need to control access to an object, typically based on permissions or roles.
Use the remote proxy when you want to represent an object located in a different address space (e.g., on a remote server) and communicate with it as if it were local.
There are more use cases of Proxy pattern. If you're interested, you can check on the internet for these proxies: firewall proxy, smart reference proxy, caching proxy, synchronization proxy, complexity hiding proxy, copy-on-write proxy, etc.
Problem
We're developing bank system. Each customer can access to any customer's account name and account number (to send money for example), but deposit, withdraw, and view balance operations should be only allowed by its account holder.
You might think we could create two classes Holder and NonHolder, then implements corresponding behavior. But notice a customer is a holder of their own bank account and non-holder of other bank account at the same time. We could implement in the way that customer can switch Holder or NonHolder at run time, but it's dangerous because now customers can be a holder of other customer's bank account.
We need a guardian to protect credential info from non-holder. Can you guess his name? That is the protection proxy!
Structure
Before going to Solution section, let's check out general (or static) proxy structure.
Dynamic proxy is the proxy that allows client to instantiate proxy at runtime. Dynamic proxy can be implemented with Java API Proxy (java.lang.reflect.Proxy).
The class diagram is a bit different from general proxy structure. Let's steps through the diagram...
Proxy now consists of two classes, Proxy and InvocationHandler classes.
Client calls a method on Proxy.
Proxy passes the method called by Client to InvocationHandler.
InvocationHandler receives the method from Proxy, and decides whether it calls the actual method on RealSubject or does alternative things.
Solution
Sorry for making you waiting for a long time, let's get into the solution.
We'll implement dynamic protection proxy.
SOCIAL SHARE CARD GENERATOR