Proxy Pattern
Learn how a stand-in object can control access to the real one, for lazy loading, security, caching and more, and how Spring uses proxies behind annotations like @Transactional.
Think about how you use money. You rarely carry the full amount of cash that you own. You carry a debit card, which is a stand-in for your bank account. When you pay, the card does not hold your money. It asks the bank, which checks your balance and your limit, and then lets the payment through or refuses it. You use the card exactly like money, but there is a gatekeeper between you and the real thing.
The Proxy pattern puts a gatekeeper in front of an object. A proxy is an object that looks exactly like the real one and stands in for it. Callers use the proxy as if it were the real object. The proxy then decides whether, when and how to pass the call on.
01Why would you put something in front of an object?
There are several common reasons, and each has its own name:
| Kind of proxy | What it does | Example |
|---|---|---|
| Virtual proxy | Creates the real object only when it is really needed (lazy loading) | A heavy image is loaded from disk only when it is first displayed |
| Protection proxy | Checks whether the caller is allowed to use the object | A document that only users with the right role may read |
| Caching proxy | Remembers earlier results and returns them without doing the work again | A slow weather lookup that is repeated for the same city |
| Remote proxy | Hides that the real object lives on another machine | A local object that sends the call over the network to a server |
| Logging or monitoring proxy | Records or measures each call | Timing how long each method takes |
Loading the rest of the lesson…