Factory Pattern

class CompressionFactory:
compression = {}
def __new__(cls):
cls.compression = {"rar": Rar(), "tar": Tar(), "zip": Zip()}
return cls

@classmethod
def getCompression(cls, method):
return cls.compression[method]

import abc
class File(abc.ABC):
def __init__(self, txt):
self.txt = txt
def __str__(self):
return self.txt


class Compression(abc.ABC):
@abc.abstractmethod
def compress(file):
pass

class Rar:
@staticmethod
def compress(file):
print(f"Rar compresstion {file}")

class Tar:
@staticmethod
def compress(file):
print(f"Tar compresstion {file}")

class Zip:
@staticmethod
def compress(file):
print(f"Zip compresstion {file}")

file = File("Text File")
factory = CompressionFactory()
CompressionFactory.getCompression("rar").compress(file)
CompressionFactory.getCompression("tar").compress(file)
CompressionFactory.getCompression("zip").compress(file)

Proxy Pattern

In proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern.

In proxy pattern, we create object having original object to interface its functionality to outer world.

import abc
class Greeter(abc.ABC):
@abc.abstractmethod
def greet(self):
pass

class RealGreeter(Greeter):
def __init__(self, name):
self.name = name
def greet(self):
return str("Hello " + self.name)

class GreaterProxy(Greeter):
greeter = None
def greet(cls, name):
# Check if the user is authorized before calling real greater
# Check real greater is available ( resources )

if cls.greeter == None:
cls.greeter = RealGreeter(name)
else:
cls.greeter.name = name
return cls.greeter.greet()

proxy = GreaterProxy()
print(proxy.greet("Chang"))

Flyweight Pattern

"""
The flyweight software design pattern refers to an object that minimizes memory usage by sharing some of its data with other similar objects.
Flyweight is a structural design pattern that lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keeping all of the data in each object.

Save Object in hashMap and used it again and again
"""
import abc
class Shape(abc.ABC):
@abc.abstractmethod
def draw(self):
pass

class Triangle(Shape):
def draw(self):
print("Triangle")

class Circle(Shape):
def __init__(self, color):
self.color = color
def setX(self, x):
self.x = x
def setY(self, y):
self.y = y
def setRadius(self, r):
self.radius = r
def draw(self):
print(f"Circle color {self.color} {self.x}:{self.y}")

class ShapeFactory:
def __init__(self):
self.circleMap = dict()
def getCircle(self, color):
if color not in self.circleMap:
self.circleMap[color] = Circle(color)
print("Creating circle of color : " + color)
return self.circleMap[color]

import random
def main():
colors = ["Red", "Green", "Blue", "White", "Black"]
circleFactory = ShapeFactory()
for i in range(50):
circle = circleFactory.getCircle(random.choice(colors))
circle.setX(random.randrange(0, 100))
circle.setY(random.randrange(0, 100))
circle.setRadius(random.randrange(0, 1000))
circle.draw()

if __name__ == "__main__":
main()
class Grade(object):
_instances = {}
def __new__(cls, percent):
percent = max(50, min(99, percent))
letter = 'FDCBA'[(percent - 50) // 10]
self = cls._instances.get(letter)
if self is None:
self = cls._instances[letter] = object.__new__(Grade)
self.letter = letter
return self

def __repr__(self):
return 'Grade {!r}'.format(self.letter)

def grademain():
print(len(Grade._instances))
for _ in range(100):
Grade(random.randint(0, 100))
print(len(Grade._instances)) # number of instances
for instance in Grade._instances.values():
print(instance)

grademain()