Flyweight Design Pattern in Python

A flyweight design pattern is a type of StructuralDesign Pattern. flyweight design aims to minimize the number of objects required in the program during the runtime. In short, it forms a flyweight instance that can be shared with multiple references. 

There is no visible difference between a normal object and a flyweight object. Flyweight objects are immutable, once constructed they cannot be modified.

Flyweight method can be easily implemented with the help of the Dictionary as it can store each object’s reference which has been created and each object is linked with the key.

Flyweight Design Pattern in Python

The diagram shows how it works

Example: Suppose you are making a game (Similar to angry birds game) and you need 5,000 red color birds and then 10000 yellow birds so you think to create 15,000 objects. Now someone used that game and he has Less RAM in his PC. The game kept on crashing because 5000 objects occupied a huge memory and will increase the size of the game and thus occupying a great memory in the RAM and if the RAM is limited, it will crash.

Solution: So you think to increase the RAM? of course not, what we can do is, we can just create one object without any color in the cache memory. Now we can easily call it and use it just by filling the color and changing the properties and it will increase our system’s performance.

So if we now need 10,000 bluebirds of different shapes, we just need to change its properties and give id and we can create it once and will be shared by all other such objects.

We can say that with the help of the Flyweight method, we as a developer can fill more objects into the available RAM by sharing mutual parts of the instance created/to be created.

3 angry birds

‎The image will help you understand better 

Advantages

  1. Less use of RAM as in this method similar objects will not take space and thus we will save a lot of memory.
  2. More the objects will decrease, more the performance will increase it nay be wherever we use.

Disadvantages

  1. We have to break encapsulation in order to move the state out of the objects.
  2. Difficult to code, it is easy to use here in Python as here all the object variables are reference but it is difficult to code in C++ where objects are local variable on stack and get erased after the action.
  3. The code complexity increases, a new developer may find it difficult to understand.

Python Code for flyweight Design Pattern

We have created a code with reference to the above bird game where we implement different object and if the id is same the object location is found the same.

Below is the code:

class SweetBirds(object): 
    #class for Birds
    def __init__(self): 
        pass
    def birds(self, bird_name): 
        return "Flyweightpattern[% s]" % (bird_name) 

class BirdKingdom(object): 
    bird_family = {}     #This stores ids of birds

    def __new__(coll,name, bird_family_ident): 
        try: 
            id = coll.bird_family[bird_family_ident] 

        except KeyError: 
            id = object.__new__(coll) 
            coll.bird_family[bird_family_ident] = id
        return id

    def put_bird_info(self, bird_info):
        #feed the  bird info

        bc = SweetBirds() 
        self.bird_info = bc.birds(bird_info) 

    def get_bird_info(self): 
        #return the bird info
        return (self.bird_info) 

if __name__ == '__main__': 

    bird_data = (('a', 1, 'Redbird'), ('b', 2, 'Yellowbird'), ('c', 2, 'Blurbird'), ('d',1,'Redbird')) 

    bird_family_objects = [] 

    for i in bird_data: 
        item = BirdKingdom(i[0], i[1]) 
        item.put_bird_info(i[2]) 

        bird_family_objects.append(item)  

    #If id same than they are same objects
    for j in bird_family_objects: 
        print(" id = " + str(id(j))) 
        print(j.get_bird_info())

You can add more properties if you want to and create as many objects we want to just by mentioning it in the dictionary.

Output

id = 500335545480
Flyweightpattern[Redbird]
id = 500336019104
Flyweightpattern[Blurbird]
id = 500336019104
Flyweightpattern[Blurbird]
id = 500335545480
Flyweightpattern[Redbird]
[Program finished]

I hope you understood the Python code and how the flyweight design pattern works. You can also try the code given in this article and if you have any doubt, you may drop a comment. Your feedback will be appreciated.

Leave a Reply