Problem Statement
Direct access to an object can cause problems like uncontrolled resource usage, security risks, or performance bottlenecks. For example, a heavy object might be created even if it is not always needed, wasting memory and CPU.
This diagram shows the client interacting with the proxy, which controls access to the real object.
### Before (no proxy) ### class RealImage: def __init__(self, filename): print(f"Loading image from {filename}") self.filename = filename def display(self): print(f"Displaying {self.filename}") image = RealImage("photo.jpg") image.display() ### After (with proxy) ### class RealImage: def __init__(self, filename): print(f"Loading image from {filename}") self.filename = filename def display(self): print(f"Displaying {self.filename}") class ProxyImage: 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() proxy_image = ProxyImage("photo.jpg") proxy_image.display() # Loads and displays proxy_image.display() # Displays without loading again