Sobes.tech
Middle

What is the design pattern Proxy (Proxy)?

sobes.tech AI

Answer from AI

The Proxy design pattern is a structural pattern that provides a surrogate or placeholder for another object to control access to it.

Proxy can be used for:

  • Lazy Initialization (Virtual Proxy): Delays the creation of a costly object until it is truly needed.
  • Access Control (Protection Proxy): Determines whether the calling object has the rights to perform an operation.
  • Logging (Logging Proxy): Records information about method calls.
  • Remote Access (Remote Proxy): Represents an object located in another address space.

Main participants:

  • Subject: An interface that defines a common contract for the real object and the proxy.
  • RealSubject: The real object that performs the work.
  • Proxy: The surrogate that has a reference to the RealSubject and controls access to it.
# Subject Interface
class Subject:
    def request(self):
        pass

# RealSubject
class RealSubject(Subject):
    def request(self):
        print("RealSubject: Handling request.")

# Proxy
class Proxy(Subject):
    def __init__(self, real_subject):
        self._real_subject = real_subject

    def request(self):
        if self._check_access():
            self._real_subject.request()
            self._log_access()

    def _check_access(self):
        print("Proxy: Checking access prior to firing a real request.")
        # Implement access control logic here
        return True

    def _log_access(self):
        print("Proxy: Logging the time of request.")
        # Implement logging logic here

# Client Code
# client_code(RealSubject()) # Direct access
# client_code(Proxy(RealSubject())) # Access through Proxy

def client_code(subject):
    subject.request()

# Example Usage
print("Client: Executing the client code with a real subject:")
client_code(RealSubject())

print("\nClient: Executing the same client code with a proxy:")
client_code(Proxy(RealSubject()))

Advantages:

  • Controls access to the object.
  • Improves performance through lazy initialization.
  • Provides remote access to objects.
  • Can add additional behavior (logging, caching) without changing the real object.

Disadvantages:

  • Can increase system complexity.
  • Method calls through the Proxy may be slower than direct calls.
What is the design pattern Proxy (Proxy)? — Python - sobes.tech