Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

Proxy Design Pattern

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:

  1. MediaPlayer interface: The Subject. This defines the contract that both the Real Subject and the Proxy must follow so the client can't tell the difference.
  2. MovieMediaPlayer class: The Real Subject. This is the expensive object that takes a long time to "load video."
  3. Proxy class: The Proxy. It holds a reference to the Real Subject. It intercepts the call to playMedia() and only creates the MovieMediaPlayer if it hasn't been created yet.
  4. Check App (Main) to see the efficiency. Notice that even though playMedia() 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.