Wednesday, March 8, 2023

The Proxy Pattern in Python...

Proxy pattern - as the name suggests - creates a proxy in place of a real heavy-duty object.

Let me give you a real-life example taken from computer science.

In case a document contains many huge-sized images, it does not load all the images when the doc gets loaded into the memory. Because it might take a very long time. 

The proxy pattern comes as a rescue. 

The document, instead of the actual mega images, gets loaded with very lightweight proxies of those images. And then when needed - in actual run time, i.e., when we need to see an image, the images get loaded by the proxy. This kind of proxy is called a virtual proxy.

Now let us talk from our example.

We are a family of three. Now my son does all the lightweight jobs - like, if there is a guest, he opens the door. So, he is the initial interface for the guests. However, in case, a guest wants to have lunch or dinner, my son calls his Mamma - because it's a heavy-duty job that he himself cannot do.

So basically my son gives proxy to his Mom, and if needed - like when he has to perform a heavy-duty job like cooking - he simply delegates the task to his Mom. For all other lightweight jobs, his Mom, who obviously has a lot of significant jobs to perform, remains in the background. She comes in the foreground in case there is a heavy-duty task like cooking for a guest.

Here's the source code of the Proxy Pattern implemented in Python.

Enjoy.


from abc import ABC,abstractmethod
class FamilyMember(ABC):
@abstractmethod
def openTheDoor(self):
pass
def cook(self):
pass

class Mamma(FamilyMember):
def openTheDoor(self):
print("Son will open the door")

def cook(self):
print("Mamma is cooking")

class Son(FamilyMember):
def __init__(self):
self.mamma = Mamma()

def openTheDoor(self):
print("Son opens the door")
def cook(self):
print("Son does not know how to cook He was just giving proxy for mamma")
self.mamma.cook()

class Home():
def __init__(self):
self.son = Son()

def openTheDoor(self):
self.son.openTheDoor()


def preparefood(self):
self.son.cook()
if __name__ == '__main__':
home = Home()
home.openTheDoor()
home.preparefood()


No comments: