Proxy

Proxy

A proxy, in its most general form, is a class functioning as an interface to something else.

Vocavulary

  • Subject Interface: Relays requests made to the proxy. The client does not know whether they are calling a proxy or the real subject as the subject interface (a form of API layer) will handle the request.
  • Real Subject: The real subject is where the core logic of the design pattern resides. The proxy can abstract a variety of fundamental security checks or cache commonly used requests, however, the subject must be in charge of most of the real functionality.
  • Proxy: Design pattern; wrapper that encapsulates access to the resource
  • Request: The function call made by the client, expecting some form of action in return from the subject. This request is sent to the interface which forwards it to the proxy. The proxy can then decide how the request should be completed.
  • Client: Component that requests data or action to be performed

Advantages

  • Increases modularity and encapsulation

Disadvantages

  • Extra developer bandwidth is required as new changes must be made in the proxy concurrently with the real object.

Implementation of Proxy pattern

  • use case: let's say we have a car that needs to be driven by a driver who is minimum of 18 years old.
  • To solve this problem, we can have the following classes

    • Car abstract class
    • Car class
    • CarProxy
from abc import ABC, abstractmethod

class CarAbs(ABC):
    @abstractmethod
    def drive(self, driver_name):
        pass

class Car(CarAbs):
    def drive(self, driver_name):
        print(f"{driver_name} is driving the car.")

class CarProxy(ABC):
    def __init__(self, driver_name, age):
        self.driver_name = driver_name
        self.age = age

    def drive(self):
        if(self.age < 18):
            print("Sorry, the driver is too young to drive.")
            return
        car = Car()
        return car.drive(self.driver_name)

if __name__ == '__main__':
    car = CarProxy("Anji", 20)
    car.drive()

    car = CarProxy("Surya", 17)
    car.drive()
  • In the above code we have a CarProxy class which checks the drivers age and calls the actual Car class.
  • CarProxy is a proxy class for Car.

Reference: