Purpose: Provide a surrogate or placeholder for another object to control access to it.
A Proxy acts as an intermediary. It allows you to perform something either before or after the request reaches the original object (like lazy loading, logging, or access control).
Use it when:
- You have a "heavy" object that is expensive to create (Virtual Proxy).
- You need to control who can access certain methods (Protection Proxy).
- You want to provide a local representation for an object in a different address space (Remote Proxy).
- You want to add a layer of logging or caching around a service.
Structure:
MediaPlayerinterface: The Subject. This defines the contract that both the Real Subject and the Proxy must follow so the client can't tell the difference.MovieMediaPlayerclass: The Real Subject. This is the expensive object that takes a long time to "load video."Proxyclass: The Proxy. It holds a reference to the Real Subject. It intercepts the call toplayMedia()and only creates theMovieMediaPlayerif it hasn't been created yet.- Check
App(Main) to see the efficiency. Notice that even thoughplayMedia()is called twice, the "Loading up large video..." message only appears once because the Proxy cached the instance.
Key Point: The Proxy pattern is about Control. The client thinks it is talking to the Real Subject, but the Proxy is managing the lifecycle of that object behind the scenes.