1ae1de6d0d2a87e6834da409bfd891b2 Proxy design pattern with python implementation

Proxy design pattern with python implementation

 


The Proxy Design Pattern is a structural design pattern that provides a surrogate or placeholder for another object to control access to it. It's used when you want to add an additional layer of control over an object without modifying its code.

Here's a visual representation of the Proxy Design Pattern. It illustrates the relationship between the Client, Proxy, and RealSubject, all structured clearly to show how the Proxy acts as an intermediary.


🧠 Core Idea:

Instead of accessing the actual object directly, you use a proxy object that performs additional operations (like access control, logging, lazy loading, etc.) before or after delegating the request to the real object.


🔧 Types of Proxy:

  1. Virtual Proxy – Controls access to a resource that is expensive to create (e.g., lazily loading large objects).

  2. Protection Proxy – Controls access by checking permissions (e.g., role-based access).

  3. Remote Proxy – Represents an object that exists in a different address space (like over a network).

  4. Smart Proxy – Adds extra functionality (e.g., reference counting, logging, caching) when accessing an object.


🧱 Structure:


Client --> Proxy --> RealSubject
  • Subject – Common interface for RealSubject and Proxy.

  • RealSubject – The actual object that does the work.

  • Proxy – Controls access to RealSubject.


🧑‍💻 Example in Pseudocode (Virtual Proxy):

class Image: def display(self): pass class RealImage(Image): def __init__(self, filename): self.filename = filename self.load_from_disk() def load_from_disk(self): print(f"Loading {self.filename}") def display(self): print(f"Displaying {self.filename}") class ProxyImage(Image): def __init__(self, filename): self.filename = filename self.real_image = None def display(self): if self.real_image is None: self.real_image = RealImage(self.filename) self.real_image.display() # Usage image = ProxyImage("photo.jpg") image.display() # Loads and displays image.display() # Just displays

Here's a simple Java implementation of the Proxy Design Pattern, using the classic Virtual Proxy example where an image is loaded only when needed.


🧱 Step-by-step Components:

1. Subject Interface


public interface Image { void display(); }

2. RealSubject (RealImage)


public class RealImage implements Image { private String filename; public RealImage(String filename) { this.filename = filename; loadFromDisk(); } private void loadFromDisk() { System.out.println("Loading " + filename); } @Override public void display() { System.out.println("Displaying " + filename); } }

3. Proxy (ProxyImage)


public class ProxyImage implements Image { private RealImage realImage; private String filename; public ProxyImage(String filename) { this.filename = filename; } @Override public void display() { if (realImage == null) { realImage = new RealImage(filename); // Lazy initialization } realImage.display(); } }

4. Client Code


public class Main { public static void main(String[] args) { Image image = new ProxyImage("photo.jpg"); // Image will be loaded and displayed image.display(); // Image will not be loaded again, only displayed image.display(); } }

✅ Output:


Loading photo.jpg Displaying photo.jpg Displaying photo.jpg



✅ When to Use:

  • Object creation is expensive or resource-intensive.

  • Need access control or permission checks.

  • Need to log access or count references.

  • Want to interact with remote resources transparently.




The Proxy Design Pattern is part of a larger family of design patterns,

and its uniqueness comes from its intent and structure compared to others.

Here's a breakdown of how Proxy differs from some commonly used design patterns:


🔍 1. Proxy vs. Decorator

AspectProxyDecorator
IntentControl access to an objectAdd behavior to an object dynamically
FocusAccess control, lazy loading, etc.Enhancing functionality
Substitute Object?Yes – acts as a stand-in for real objectNo – wraps the object to add features
Example UseVirtual proxy, security proxyAdding logging, compression, encryption

Think of Proxy as a gatekeeper; Decorator as a feature extender.


🔧 2. Proxy vs. Adapter

AspectProxyAdapter
IntentControl access to an objectConvert one interface into another
Main GoalIndirect access with possible checksInterface compatibility
Does it change the interface?No – maintains the original interfaceYes – adapts to a different one

Proxy preserves the interface; Adapter reshapes it.


🏗️ 3. Proxy vs. Facade

AspectProxyFacade
IntentAct as an intermediaryProvide a simplified interface
Main GoalAccess control, logging, lazy loadingSimplify complex subsystem usage
Used For?Object-level controlSystem-level abstraction

Proxy sits in front of an object; Facade sits in front of a system.


🧱 4. Proxy vs. Singleton

AspectProxySingleton
IntentControl access to another objectEnsure a class has only one instance
PurposeIntercept or defer real object useGlobal instance control

Proxy manages interaction; Singleton manages existence.


🧠 TL;DR - What Makes Proxy Unique?

  • Acts on behalf of another object.

  • Focuses on access control, performance (via lazy loading), or network communication.

  • Maintains the same interface as the original object.


Post a Comment

0 Comments