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):
def draw(self):

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

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

if __name__ == "__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():
for _ in range(100):
Grade(random.randint(0, 100))
print(len(Grade._instances)) # number of instances
for instance in Grade._instances.values():


Leave a Reply