Implementing the Proxy pattern using Python
The Proxy pattern is a structural design pattern that allows indirect access to another object by creating a proxy object. The Proxy pattern can reduce the coupling of the system and increase the flexibility of the code. The following is a complete sample code for implementing the Proxy pattern in Python: ```python #In this example, we will restrict access to the original object through a proxy object #Define a raw object interface class Image: def display(self): pass #Define the original object class class RealImage(Image): def __init__(self, filename): self._filename = filename self.load_from_disk() def load_from_disk(self): print("Loading image: " + self._filename) def display(self): print("Displaying image: " + self._filename) #Defining Proxy Object Classes class ProxyImage(Image): 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() #Using Proxy Objects image = ProxyImage("example.jpg") #The original object will be loaded on the first access image.display() #Directly use the original object for the second and subsequent access image.display() ``` In the above example, 'RealImage' is a primitive object class that implements the 'Image' interface, representing the true image object` ProxyImage 'is a proxy object class that also implements the' Image 'interface, which includes references to' RealImage 'and creates' RealImage' objects when needed to handle the actual image display. By using proxy objects, we can control and manage the original objects when needed, such as implementing delayed loading of images or restricting image access permissions. In the sample code above, we used lazy loading method, which only loads the original object the first time the 'display()' method is called. In the second and subsequent calls, directly using the already loaded original objects improves the performance and efficiency of the system. The output result is: ``` Loading image: example.jpg Displaying image: example.jpg Displaying image: example.jpg ```