04 Dec 2023



Intermediate

The Proxy Design Pattern is a structural design pattern that lets you provide a substitute or placeholder for another object. It acts as an intermediary between the client and the real object, controlling access to it and providing additional functionality.

In simpler terms, a proxy is like a personal assistant who handles your interactions with another person. It can filter requests, manage permissions, and even perform tasks on your behalf.

key points of the Proxy Design Pattern:

  1. Intent:

    • The main intent of the Proxy pattern is to provide a surrogate or placeholder for another object to control access to it. It adds an additional layer of indirection to manage access to the real object.
  2. Key Components:

    • Subject:
      • Defines the common interface for the RealSubject and Proxy so that a Proxy can be used wherever a RealSubject is expected.
    • RealSubject:
      • Represents the real object that the Proxy controls access to. It defines the functionality that the Proxy can represent.
    • Proxy:
      • Maintains a reference to the RealSubject and provides an interface that is identical to the Subject. It controls access to the RealSubject and may perform additional tasks.
  3. Types of Proxies:

    • Virtual Proxy:
      • Delays the creation and initialization of the RealSubject until the moment it is actually needed.
    • Protection Proxy:
      • Controls access to methods or operations of the RealSubject by adding additional checks or restrictions.
    • Remote Proxy:
      • Represents an object that is in a different address space. It acts as a local representative to the real object, handling communication and data marshaling.
    • Cache Proxy:
      • Manages caching of the results obtained from the RealSubject to improve performance.
  4. Lazy Loading:

    • Proxies can be designed to load the RealSubject only when needed, which is useful for resource-intensive objects.
  5. Advantages:

    • Control Access: The Proxy pattern allows for controlling access to the real object, adding an extra layer of control.
    • Enhanced Functionality: Proxies can add functionality such as logging, security checks, or caching without modifying the RealSubject.
  6. Use Cases:

    • The Proxy pattern is useful when you want to control access to an object, add additional functionality before or after access, or delay the creation of the real object until it is actually needed.

Example:

  • Consider a scenario where you have an interface for an image loader (Subject), a real image loader (RealSubject) that loads images from a database, and a proxy image loader (Proxy) that adds functionality like caching or access control.
software-design-patterns
proxy-design-pattern