Thursday, March 9, 2023

Observer Pattern in Python...

The observer design pattern is a very popular design pattern in the Object Oriented world. I must admit, I first saw the utilities of this design pattern while studying the document view architecture of the MFC source code.

Later on, I used this pattern in many places.

There is a lot of similarity between the Observer Pattern, the Callback mechanism, and the Event Handler process in Java. Usually, the callback method is used when there is only one observer who awaits the signal from the observee.

So, let me put it in this fashion.

Suppose, there is a central document that is viewed by a few applications - someone is viewing it in a spreadsheet, someone as a Pie chart, and so on.

Now if the data in the document is updated, all the viewers must be updated and they should synchronize their views with the latest data set. So basically all the viewers were observing the central data. The moment it changes, all the observers get their respective views updated.

Here goes the Python code for this observer pattern

from __future__ import annotations

from abc import ABC,abstractmethod

from typing import List

class Subject(ABC):

   @abstractmethod

   def addObserver(self,observer):

       pass

   @abstractmethod

   def removeObserver(self,observer):

       pass

   @abstractmethod

   def notifyObservers(self):

       pass

class ConcreteSubject(Subject):

   _observers = []

   _state = "my current state"

   def addObserver(self,observer):

       self._observers.append(observer)

   def removeObserver(self,observer):

       self._observers.remove(observer)

   def notifyObservers(self):

       for observer in self._observers:

           observer.update()

   def dosomething(self):

       print("I am doing something which will change my state.Notifying observers")

       self._state = "subject state has been changed"

       self.notifyObservers()

class Observer(ABC):

   @abstractmethod

   def update(self):

       pass

class ConcreteObserver(Observer):

   def __init__(self,subject):

       self._subject = subject

   def update(self):

       print(self._subject._state)

if __name__ == '__main__':

   concretesubject = ConcreteSubject()

   observer1 = ConcreteObserver(concretesubject)

   observer2 = ConcreteObserver(concretesubject)

   concretesubject.addObserver(observer1)

   concretesubject.addObserver(observer2)

   concretesubject.dosomething()


For all other inquisitive student communities, here goes my training on Observer Pattern in Java


And for all the Bengali medium students, here we go


Observer Pattern in Bengali...

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()


The State Pattern in Python...

 In the State Design Pattern, the same object behaves differently depending on the current state of the object.

For example, take the case of Chicken preparation.

When it is delivered, it remains in an uncleaned state. Hence the first task will be to clean it. 

At that time if you call a specific method of the Chicken State, say, cook, it will behave differently (say maybe flash out a message that the chicken can't be cooked until it is properly cleaned and marinated). But the same cook method will cook the chicken once it is in the Marinated State. This time the "cook" method will properly cook the chicken and will flash out a different message - maybe like the Chicken is getting cooked - so have patience.

In the example, we have a ChickenState interface and then Mamma as the chef. The transition from one state to another is done at the end of the appropriate method of the interface at each state.

Enjoy the State Pattern written in written in Python


from __future__ import annotations
from abc import ABC, abstractmethod
import time

class Mamma():
def __init__(self, state):
self._state = state


def getstate(self):
return self._state


def setstate(self, state):
self._state = state


def startpreparation(self):
self._state.wash()
self._state.marinate()
self._state.cook()
self._state.serve()




class State(ABC):
@abstractmethod
def wash(self):
pass


@abstractmethod
def marinate(self):
pass


@abstractmethod
def cook(self):
pass


@abstractmethod
def serve(self):
pass




class UncleanedState(State):
def __init__(self, mamma):
self._mamma = mamma


def wash(self):
print("chicken is in the uncleaned state and is getting cleaned:next state will be cleaned state")
time.sleep(1)
self._mamma.setstate(CleanedState(self._mamma))


def marinate(self):
print("chicken is in the uncleaned state...first clean it")
pass


def cook(self):
print("chicken is in the uncleaned state...first clean it")
pass


def serve(self):
print("chicken is in the uncleaned state...first clean it")
pass




class CleanedState(State):
def __init__(self, mamma):
self._mamma = mamma


def wash(self):
print("chicken is in the cleaned state...wash already done")
pass


def marinate(self):
print("chicken is in the cleaned state and is marinated. next state will be marinate state")
time.sleep(1)
self._mamma.setstate(MarinateState(self._mamma))


def cook(self):
print("chicken is in the cleaned state...first marinate it")
pass


def serve(self):
print("chicken is in the cleaned state...first marinate it")
pass




class MarinateState(State):
def __init__(self, mamma):
self._mamma = mamma


def wash(self):
print("chicken is in the marinated state...cleaning already done")
pass


def marinate(self):
print("chicken is in the marinated state...marination already done")
pass


def cook(self):
print("chicken is in the marinated state and being cooked. :next state will be cooked state")
time.sleep(1)
self._mamma.setstate(CookedState(self._mamma))


def serve(self):
print("chicken is in the marinated state and being cooked. only after cooking u can serve...")
pass




class CookedState(State):
def __init__(self, mamma):
self._mamma = mamma


def wash(self):
print("chicken has already being cooked")
pass


def marinate(self):
print("chicken has already being cooked")
pass


def cook(self):
print("chicken has already being cooked")
pass


def serve(self):
print("chicken is ready and is served : this is the last state")
time.sleep(1)


print("guest are saying thank you for the meal")


if __name__ == '__main__':
mamma = Mamma(None)
mamma.setstate(UncleanedState(mamma))
mamma.startpreparation()







Tuesday, March 7, 2023

The Command Pattern in Python...

When I taught my son #Ridit and many other students about Python, I had to cover the subject of the Design Patterns implemented in Python.

Here we go. - the Command Pattern being implemented in Python.

We have taken the same Restaurant problem which has Chef, Waiter, and Order classes participating in this design pattern.

The idea of Command Pattern is that the decoupling between the invoker of the command and the executor.

The command is kind of a full-fledged object having all knowledge about the executor of the command meaning the command will have a reference to the executor of the command.

The waiter is working as the invoker and the chef is working as the executor of the command.

Here we go.

The Source Code


from abc import ABC , abstractmethod
import time
class Item:
    def __init__(self,name,price):
        self.name = name
        self.price = price
class ItemOrder:
    def __init__(self,item,numberOfPlates):
        self.item = item
        self.numberOfPlates = numberOfPlates
class Order:
    def __init__(self):
    	self.itemorders = []
    def getItemOrder(self):
        return self.itemorders
#executor
class Chef(ABC):
    @abstractmethod
    def prepare(self):
        pass


class ChefTeaCoffe(Chef):
    def prepare(self,order):
        for itemorder in order.itemorders:
            if "Tea" in itemorder.item.name:
                print(str(itemorder.numberOfPlates) + " cups of " + itemorder.item.name + " is being prepared")
                time.sleep(5)
                

class ChefFood(Chef):
    def prepare(self,order):
        for itemorder in order.itemorders:
            if "Food" in itemorder.item.name:
                print(str(itemorder.numberOfPlates) + " plates of " + itemorder.item.name + " is being prepared")
                time.sleep(5)
                
#command
class Command(ABC):
    @abstractmethod
    def execute(self):
        pass
class TeaCoffeeCommand(Command):
    def __init__(self,chef,order):
        self.chef = chef
        self.order = order

    def execute(self):
        self.chef.prepare(self.order)

class FoodCommand(Command):
    def __init__(self,chef,order):
        self.chef = chef
        self.order = order

    def execute(self):
        self.chef.prepare(self.order)
#invoker
class Waiter:
    def setCommand(self,command):
        self.command = command

    def giveCommandToChef(self):
        self.command.execute()


if __name__ == '__main__':
    itemTea = Item("Tea",40)

    itemBread = Item("Food", 20)

    itemOrderTea = ItemOrder(itemTea, 3)

    itemOrderBread = ItemOrder(itemBread, 4)

    orderTea = Order()
    orderFood = Order()

    orderTea.itemorders.append(itemOrderTea)
    orderFood.itemorders.append(itemOrderBread)

    chefTea = ChefTeaCoffe()
    chefFood = ChefFood()

    commandTeaCoffee = TeaCoffeeCommand(chefTea, orderTea)
    commandFood = FoodCommand(chefFood, orderFood)

    waiter = Waiter()
    waiter.setCommand(commandTeaCoffee)
    waiter.giveCommandToChef()

    waiter.setCommand(commandFood)
    waiter.giveCommandToChef()

Here is my son, Ridit, explaining the command design pattern implemented in Python.
I hope you will like it.



Monday, February 6, 2023

Thursday, January 12, 2023

A little ray of Hope at the end of the tunnel - a little progress in the journey of Fluid Simulation...




There is no shortcut to success...


It depends on sheer hard work, burning the midnight oil in front of the computer, and of course, luck and destiny...

On this auspicious day of Swami Vivekananda's birthday, I am reiterating my faith in #karmyog - this is the best way to ward off depression, loneliness, and all sorts of modern-day psychological hazards - the best way to attain #wisdom

Once the purpose of a person's life is attuned to his/her skill and ability - there won't be any looking back for that person.

I remember, one of the reasons for my coming to the software world was the hollowness of my job at the Indian corporate headquarter of a Fortune 25 company (at that time).

I used to say it loud that most of us at the junior level till the high and middle management level are simply busy doing time pass activities all through the day - wasting a lot of company resources by making useless presentations and all sorts of time passing documents just to showcase that we are all playing important roles in the company - whereas the multi-million dollar deal will most probably be done at the golf club and in between the top boss of the telecom service provider and the top boss from the mother organization of the transnational company.

So why waste time there?

Rather it was good to choose a profession where I can enjoy the result of my karma instantly on the monitor of the computer.

In the age when there was no Google, it was a difficult decision for me - however, the risk was worth to be considered.

I remember after I joined the software bandwagon and started understanding the nitty-gritty of Object-Oriented Software, the major hurdle was to decipher what the ## (double hashes) does in C++ (it was part of the boilerplate code of the MFC/VC++ message_map macro) which was automatically produced by the wizard.

And as there was no #Google, I had to wait quite a long before it became clear to me. Later, when I was deciphering the service framework code of the Android, I found similar code and I thanked my inquisitive nature that I was able to showcase in the beginning.

Knowledge is all-powerful and it makes one a really interesting person.