Reading Time: 1 minutes
Proxy Design Pattern in Python
Write a Python program to implement Proxy Design Pattern.
class Car:
'''Resource-intensive object'''
def driveCar(self):
print("Driving Car....")
class CarProxy:
'''Relatively less resource-intensive proxy acting as middleman. Instantiates a Car object only if the driver is of age.'''
def __init__(self):
self.ageOfDriver = 15
self.car = None
def driveCar(self):
print("Proxy in action. Checking to see if the driver is of age or underage...")
if self.ageOfDriver >= 18:
# If driver is of age, let him drive the car.
self.car = Car()
self.car.driveCar()
else:
# Otherwise, don't instantiate the car object.
print("Driver is underage. Can't drive the car.")
# Instantiate the Proxy
carProxy = CarProxy()
# Client attempting to drive a car at the default age of 15. Logically, since he/she cannot have a driving license, there is no need to buy a car, or, in our case, make the car object.
carProxy.driveCar()
# OUTPUT:
# Proxy in action. Checking to see if the driver is of age or underage...
# Driver is underage. Can't drive the car.
# Altering the age of the driver
carProxy.ageOfDriver = 21
# Client attempting to drive a car at the default age of 21. Should succeed.
carProxy.driveCar()
# OUTPUT:
# Proxy in action. Checking to see if the driver is of age or underage...
# Driving Car....







