Flyweight Pattern


In this article we are discussing the Flyweight Design Pattern. It is one among the 23 design patterns and provides an improved way of managing objects.

Challenge

You are working on an Id Card Creation web application. The application has 1 lakh Student records for which Id Cards to be created.

The following is the StudentCard class that performs the id card generation. We need to call the GenerateIdCard() method to get the Id Card image after assigning the student Name, Address, Photo properties. Each card image generated is saved to file system.

Flyprtn1.gif

The problem is the 1 Lakh class instances created. How to reduce the number of instances?

Definition

"Use sharing to support large numbers of fine-grained objects efficiently."

Implementation

Using the Flyweight pattern, we can solve the above problem. We can see from the above problem that at a time only one instance is needed.

We can use only one instance of StudentCard class and share it inside the loop to assign the properties and generate id card.

The pattern is advisable on:

  • To reduce the number of instances
  • Sharing properties which are common

This was the old process:

Flyprtn2.gif

Here depending on the Student count, instances of StudentCard are created.

This will be the new process:

Flyprtn3.gif

Here only 1 instance of StudentCard is created.

Code View

Following is the code implementing Flyweight pattern:

StudentCard card = new StudentCard();
card.CollegeName = "College of Advanced Sciences"; // CommonProp

for (int i = 1; i <= 100; i++)
{
    card.Name = names[random.Next(0, names.Length - 1)];
    card.Address = addresses[random.Next(0, addresses.Length - 1)];
    card.Photo = photos[random.Next(0, photos.Length - 1)];

    list.Add(new System.Web.UI.WebControls.Image()
        {
            ImageUrl = card.GenerateIdCard()
        });
}

Screen Shot

On running the attached web application you can see the following output. The data like Name, Address and Photo are randomly generated.

Flyprtn4.gif

Drawbacks

Although the Flyweight pattern solves many problems, I would like to list some of the possible drawbacks of using it.

  • More configuration code is needed to switch between properties

  • Reduces performance in a multi-threaded environment if locks are used

Summary

In this article we have explored Flyweight design pattern. The pattern helps us in reducing system resources if correctly used. The associated source code contains the example we have discussed. Please let me know your comments on the article.
 


Similar Articles