Open In App

Flyweight Method – Python Design Patterns

Flyweight method is a Structural Design Pattern that focus on minimizing the number of objects that are required by the program at the run-time. Basically, it creates a Flyweight object which is shared by multiple contexts. It is created in such a fashion that you can not distinguish between an object and a Flyweight Object. One important feature of flyweight objects is that they are immutable. This means that they cannot be modified once they have been constructed.
To implement the Flyweight method in Python, we use Dictionary that stores reference to the object which have already been created, every object is associated with a key.
 

Why we do care for the number of objects in our program ?

 



 

Problem without using Flyweight Method

Imagine you are a game developer who likes Racing Games much and also wants to develop a racing game for you and your friend. As you are a flawless Game developer, you created one and start enjoying the game. Then you sent the game to your friend also but he did not enjoy the game too much because the game kept crashing after every few minutes. 
But Why? ( Guess the reason if you think you are a Pro Game Developer).After debugging for several hours, you found that the issue is lack of RAM on your friend’s system. Your system is much powerful as compared to your friend’s system that’s why the game was running smoothly on your system but not on your friend’s system.
 



Flyweight-problem-Diagram

 

Solution using Flyweight Method

so, what will you do as a developer to improve the performance? (of course! not going to upgrade the RAM).The actual problem is related to car objects because each car is represented by separate objects containing plenty of data related to its color, size, seats, maximum speed, etc. Whenever your RAM got filled and unable to add more new objects which are required currently, your game gets crashed. For avoiding such situations in applications, it is the prior duty of the developer to use Flyweight Method which allows you to fit more objects into the available amount of RAM by sharing common parts of the objects.
 

Following Code is written using the Flyweight method
 




class ComplexCars(object):
 
    """Separate class for Complex Cars"""
 
    def __init__(self):
 
        pass
 
    def cars(self, car_name):
 
        return "ComplexPattern[% s]" % (car_name)
 
 
class CarFamilies(object):
 
    """dictionary to store ids of the car"""
 
    car_family = {}
 
    def __new__(cls, name, car_family_id):
        try:
            id = cls.car_family[car_family_id]
        except KeyError:
            id = object.__new__(cls)
            cls.car_family[car_family_id] = id
        return id
 
    def set_car_info(self, car_info):
 
        """set the car information"""
 
        cg = ComplexCars()
        self.car_info = cg.cars(car_info)
 
    def get_car_info(self):
 
        """return the car information"""
 
        return (self.car_info)
 
 
 
if __name__ == '__main__':
    car_data = (('a', 1, 'Audi'), ('a', 2, 'Ferrari'), ('b', 1, 'Audi'))
    car_family_objects = []
    for i in car_data:
        obj = CarFamilies(i[0], i[1])
        obj.set_car_info(i[2])
        car_family_objects.append(obj)
 
    """similar id's says that they are same objects """
 
    for i in car_family_objects:
        print("id = " + str(id(i)))
        print(i.get_car_info())

Output

id = 58598800
ComplexPattern[Audi]
id = 58598832
ComplexPattern[Ferrari]
id = 58598800
ComplexPattern[Audi]

Class diagram

Following is the class diagram for the Flyweight method
 

Flyweight-class-diagram

 

Advantages

 

 

Disadvantages

 

 

Applicability

 

Further Read – Flyweight Method in Java
 


Article Tags :