Friday, August 18, 2023

Composite Design Pattern in Python....

 When I first started studying the Gang of Four book back in 2003-2004, it was an absolutely new thing to me. I must admit today that not everything became clear at that time. But gradually, the knowledge is being imbibed, and now while teaching my young son Ridit on this subject, I just love it.

Moreover, as I am now comfortable with three languages namely C++, Java, and Python, recreating the stuff for various languages looks pretty easy now.

So, today, I am rewriting the Composite Design Pattern in Python. Here goes my original Composite Design pattern implemented using C++ and written in 2008.





And here goes the exploration of the Composite Design Pattern by my young son, Ridit, currently a class VII student.



And here goes the Composite Design Pattern implemented in Python.

I hope you will like it.

from abc import ABC, abstractmethod

class Shape(ABC):

def __init__(self):
self.parent = None
@abstractmethod
def add(self, shape):
pass

@abstractmethod
def remove(self, shape):
pass

def getparent(self):
return self.parent

def setparent(self, parent):
self.parent = parent

@abstractmethod
def display(self):
pass


class CompositeShape(Shape):
def __init__(self):
self.listofShapes = []

def add(self, shape):
shape.setparent(self)
self.listofShapes.append(shape)


def remove(self, shape):
self.listofShapes.remove(shape)
shape.setparent(None)

def setParent(self, parent):
self.parent = parent

def display(self):
pass


class Point(Shape):
def __init__(self, x, y):
self.x = x
self.y = y

def display(self):
print ("X = ", self.x, "Y = ", self.y)

def add(self, shape):
print("This is a leaf class.... Can't add to it...")

def remove(self, shape):
print("This is a leaf class.... Can't remove from it...")

class Line(CompositeShape):
def __init__(self, p1, p2):
super().__init__()
self.add(p1)
self.add(p2)

def display(self):
print("The starting and end points of the line are")
for shape in self.listofShapes:
shape.display()

class Quadrilateral(CompositeShape):
def __init__(self, p1,p2,p3,p4):
super().__init__()
self.add(p1)
self.add(p2)
self.add(p3)
self.add(p4)

def display(self):
print("The four corners of the quadrilateral are ")
for shape in self.listofShapes:
shape.display()


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
p1 = Point(10,20)
p2 = Point(30,40)
p3 = Point(50,60)
p4 = Point(70,80)

p1.add(p2)

L1 = Line(p1,p2)
q1 = Quadrilateral(p1,p2,p3,p4)

p1.display()
p2.display()
L1.display()

q1.display()

If we execute the above code, the console window will display the following result


This is a leaf class... Can't add to it...
X =  10 Y =  20
X =  30 Y =  40
The starting and end points of the line are
X =  10 Y =  20
X =  30 Y =  40
The four corners of the quadrilateral are 
X =  10 Y =  20
X =  30 Y =  40
X =  50 Y =  60
X =  70 Y =  80

Wednesday, August 16, 2023

Chain Of Responsibility in Python...

 In this design pattern, there are some sorts of executors of a command tied in a chain - at different levels. Depending upon the complexity of the task, the command is handled at different levels. Each receiver is well aware of if he can handle the command. If he can't he simply passes the buck to the next person in the chain. Once the command reaches the highest level of the chain, it must be handled there as there is no more successor after the highest authority.

The idea is that the command is always delivered at the lowest level of the chain and then it moves forward - one step at a time till it is handled at one such level.

Here is the class diagram of the Chain of Responsibility design pattern.


Here goes the source code of the chain of responsibility implemented in Python...

from abc import ABC, abstractmethod


class ICommand(ABC):
def __init__(self, level):
self.level = level


class CommandReceiver(ABC):
def __init__(self, successor):
self.successor = successor


@abstractmethod
def handleCommandImpl(self, command):
pass

def handleCommand(self, command):
retType = self.handleCommandImpl(command)
if self.successor != None and retType == False:
self.successor.handleCommand(command)
else:
return



class ReceiverLevel1(CommandReceiver):
def __init__(self, successor):
self.successor = successor

def handleCommandImpl(self, command):
if command.level == 1:
print("The Command is handled at level 1")
return True
else:
print("Forwarding the command from level 1 to level 2")
return False


class ReceiverLevel2(CommandReceiver):
def __init__(self, successor):
self.successor = successor

def handleCommandImpl(self, command):
if command.level == 2:
print("The Command is handled at level 2")
return True
else:
print("Forwarding the command from level 2 to level 3")
return False


class ReceiverLevel3(CommandReceiver):
def __init__(self, successor):
self.successor = successor

def handleCommandImpl(self, command):
if command.level == 3:
print("The Command is handled at level 3")
return True
else:
print("Last level... The Command has to be managed here...")
return False


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
commandLevel1 = ICommand(1)
commandLevel2 = ICommand(2)
commandLevel3 = ICommand(3)

receiverLevel3 = ReceiverLevel3(None)
receiverLevel2 = ReceiverLevel2(receiverLevel3)
receiverLevel1 = ReceiverLevel1(receiverLevel2)

receiverLevel1.handleCommand(commandLevel3)


Thursday, May 18, 2023

State Design Pattern in C++ using boost's pointer...

After a long time, I am again back to my tech domain. Please enjoy my work on State Design Pattern in C++ using boost's pointer.

Here is the class diagram of my code




Class Diagram



Saturday, April 22, 2023

The concept of an Orthodox Canonical class in C++

 


After the new release of C++ and the inclusion of boost's pointer, many original concepts of C++ had been overwritten. When I studied C++ back in the '90s, the orthodox canonical class formation was important to make a UDT behave as closely as possible to a built-in type. The orthodox canonical class must be having a default constructor, a virtual destructor, a copy constructor, and an assignment operator. These four building blocks must be there in a class before we can call it a canonical C++ class.

Here I have developed an Orthodox canonical String class in its simplest form.

I hope you will like the video of creating it.

Wednesday, March 15, 2023

Pi Day and the genius mathematician from Bharat - Ramanujan

 


The genius mathematician who used to dream Maths formulas


Ramajunan lived just 32 years - but created history in Maths which shows the brain power of Bharat.

But again, due to colonialism, we celebrated this genius once he was celebrated abroad - in England - the same way Swami Vivekananda and Rabindranath Tagore were termed genius only after they became iconic figures abroad.

The way Mozart used to visualize the music, this genius from Bharat used to dream of Maths.

The first letter he wrote to a famous British Mathematician G H Hardy, contained 120 Maths formulas but no demonstration of how he got all these formulas.

This forced the British mathematician to almost pooh-pooh Ramanujan, but in the end, even he said, all these formulas must be true - otherwise how one could ever imagine them.

Let me conclude this write-up with only one request to the Humans of Bharat - you have already wasted a very long period of time in hibernation - now it's time for you to wake up and reclaim your true spirit - the Vishwaguru Bharat.

I am really happy to see that Baharat has come up with her own designed railways locomotive - which can make even the technologies of Japan envy us. We have come up with our indigenous Kabach - the shield - to be used in the Railways as safety norms.

The possibilities are infinite.

Only we have to change the mindset - we are here to contribute to the global community as Vishwaguru Bharat.

This is the true nature of Bharat - let us change the global perception of Bharat

From the takers to the givers

we have a lot of stuff to give to the UNIVERSE - just as Vishwaguru Bharat

Jai Hind...

Monday, March 13, 2023

A new journey restarted - the beginner's step - Monte Carlo Methpd

Monte Carlo Simulation, also known as the Monte Carlo Method or a multiple probability simulation, is a mathematical technique, which is used to estimate the possible outcomes of an uncertain event. The Monte Carlo Method was invented by John von Neumann and Stanislaw Ulam during World War II to improve decision-making under uncertain conditions.


Unlike a normal forecasting model, Monte Carlo Simulation predicts a set of outcomes based on an estimated range of values versus a set of fixed input values.

Example 1

Problem: the probability of three heads and two tails for a coin tossed five times (assuming a fair coin)

# Answer (from Maths Probability theory) : binomial(3 + 2, 3) 2^(-(3 + 2)) = ((3 + 2)!)/(3! 2! 2^(3 + 2))= 5/16 ≈ 0.3125

Example 2

Problem: The probability of getting three consecutive Heads at the beginning if a coin is tossed 5 times

# Answer (Using Probability theory): ½ X ½ X 1/2  = ⅛ = 0.125


The Mathematical model of Monte Carlo written in Python

Problem 1

def calculateprobability1(attempts):
success = 0
for i in range(0, attempts):
if (random.randint(0, 1) + random.randint(0, 1) +
random.randint(0, 1) + random.randint(0, 1)
+ random.randint(
0, 1)) != 3:
pass
else:
success += 1
print("Number of attempts = ", attempts)
print("Number of success = ", success)

return success / attempts


Problem 2

def calculateprobability2(attempts):
success = 0
for i in range(0, attempts):
if (random.randint(0, 1) == 1 and random.randint(0, 1) == 1
and random.randint(0, 1) == 1):
success += 1
else:
pass
print("Number of attempts = ", attempts)
print("Number of success = ", success)

return success / attempts



The Monte Carlo examples implemented in Python...

Thursday, March 9, 2023

Factory Pattern in Python...

 I used to get the utmost satisfaction by deciphering framework code. I remember, initially, I used to study the MFC framework code and came to know about observer patterns, about the chain of responsibility design patterns being used there.

Later, I used to study the Symbian S60 framework code - and studied in detail their Active Object design principles and ECom plugins.

Yes, I am talking about 2006-2007 just before the arrival of the iPhone and Android when NOKIA was the undisputed leader in the mobile world.

Please have a look at the following blog post where I deciphered the basic Active Object of the Symbian framework and why a long-running task does not freeze the UI.

So the point is, don't blindly follow anything. Keep your inquisitive mind always ready for new stuff. For example, my inquisition about the two-phase constructor in Symbian led me to study the Boost library in 2007 in Japan which ultimately became part of the C++ standard library in the 2009 release of C++.

Symbian Active Object framework...




Then when i switched over to Android, I started studying the Android framework code.

For example here are two such detailed study analyses on Asynctask and Android Service Framework


Asynstask Framework...




Android Service internals...




This has changed my mindset from looking at code from just a programmer's perspective. I try to find out the design principles and try to join the invisible dots inside the framework code.

For example, when i found the parameterized factory pattern implementation in the Android framework code, my vision becomes clearer than the vision of a programmer.

Please have a look at the following document where i studied that part of the Android media framework where the parameterized factory pattern is used.






So, here we go - an implementation of Factory Pattern in Python.

from abc import ABC,abstractmethod


class Food(ABC):

   pass

class Chocolate(Food):

   def __init__(self):

       print("chocolate is made")

class Biscuit(Food):

   def __init__(self):

       print("biscuit is made")


class Factory:

   def makefood(self,type):

       if(type == "ch"):

           return Chocolate()

       if(type == "bi"):

           return Biscuit()

if __name__ == '__main__':

   fact = Factory()

   chocolate = fact.makefood("ch")

   biscuit = fact.makefood("bi")



Friends... Enjoy...
Just start deciphering a framework code...
And become happy in your endeavor...