FlyWeight Method

FlyWeight Method

Flyweight Method

Flyweight method is a type of structural design pattern that allows reduction in the number of objects that are required by the program at run-time. This method creates a flyweight object which is shared by multiple contexts, and once the flyweight class constructs the object, it cannot be modified again, and this is called Immutable. This method saves RAM by caching the same data used by different objects.

In the flyweight method, The class divides in two-parts:

  • The Intrinsic State
    • it’s a field that contains constant data duplicated across many objects
  • The Extrinsic State
    • it’s a field that contains contextual data unique to every object.

The following is the guidelines for implementing the Flyweight method:

  • First, divide the class into intrinsic state and extrinsic state.
  • Set aside the class that represents the intrinsic state so to which the objects there are immutable.
  • Introduce a new parameter for each field in the extrinsic state.
  • By choice, try to manage the pool of flyweight create a factory class for them all.
  • Allow the client to store values of the extrinsic state so to be able to call the flyweight objects methods.
Code Implementation

The following is the code implementation of the Flyweight method in Python:

class ComplexBike(object):
    """ Seperate class for Complex bikes """
    def __init__(self):
    def bikes(self, bike_name):
        return "ComplexPattern {}".format(bike_name)

class BikeFarmilies(object):
    """ dictioary to store ids of the bike  """
    bike_family = {}
    def __new__(cls, name, bike_family_id):
            id = cls.bike_family[bike_family_id]
        except KeyError:
            id = object.__new__(cls)
            cls.bike_family[bike_family_id] = id
        return id
    def set_bike_info(self, bike_info):
        """ set the bike information """
        cg = ComplexBike()
        self.bike_info = cg.bikes(bike_info)
    def get_bike_info(self):
        """ return the bike information """
        return (self.bike_info)

if __name__ == '__main__':
    bike_data = (('a',1,'TVS'), ('a', 2, 'MxPro'), ('b', 1, 'BMax'))
    bike_family_objects = []
    for i in bike_data:
        obj = BikeFarmilies(i[0], i[1]) 

    """similar id's says that they are same objects """
    for i in bike_family_objects: 
        print("\n id = " + str(id(i)) + "\n") 

Code output:

[email protected]:~/Desktop/InfosecAddicts/python design pattern$ python

id = 140452134359440

Complex Pattern BMax

id = 140452134359504

Complex Pattern MxPro

id = 140452134359440

Complex Pattern BMax

Pros and Cons

  • Improvement in Data Caching
  • Performance Improved
  • Loss usage of RAM
  • Code Complication
  • Encapsulation Breakage
  • Very hard to handle.