Fly weight pattern is useful where we need to create many objects and all these objects share some kind of common data. Consider figure ‘Objects and common data’. We need to print visiting card for all employees in the organization. So we have two parts of data one is the variable data i.e. the employee name and the other is static data i.e. address. We can minimize memory by just keeping one copy of the static data and referencing the same data in all objects of variable data. So we create different copies of variable data, but reference the same copy of static data. With this we can optimally use the memory.
Figure: - Objects and common data
Below is a sample C# code demonstration of how flyweight can be implemented practically. We have two classes, ‘clsVariableAddress’ which has the variable data and second ‘clsAddress’ which has the static data. To ensure that we have only one instance of ‘clsAddress’ we have made a wrapper class ‘clsStatic’ and created a static instance of the ‘clsAddress’ class. This object is aggregated in the ‘clsVariableAddress’ class.
Figure: - Class view of flyweight
Figure ‘Fly weight client code’ shows we have created two objects of ‘clsVariableAddress’ class, but internally the static data i.e. the address is referred to only one instance.
Figure: - Fly weight client code
Asked In: Many Interviews |