Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Flyweight Design Pattern

, 4 May 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Flyweight Design Pattern clearly explained with example

You can see this and other great articles on design patterns here

The flyweight design pattern allows you to reuse memory spaces in an application when you have lots of objects that are almost identical in nature. For example, if you are writing a game for a Smartphone where the amount of memory is very limited and you need to show many aliens that are identical in shape, you can have only one place that holds the shape of the alien instead of keeping each identical shape in the precious memory.

In the flyweight pattern, there is the concept of Intrinsic and Extrinsic state. Intrinsic states are things that are constant and are stored in the memory. Extrinsic states are things that are not constant and need to be calculated on the fly, and are therefore not stored in the memory.

For example, in the game that we would like to create, the shapes of the aliens are all the same, but their color will change based on how mad each are. The shapes of the aliens will be Intrinsic, and the color of the alien will be Extrinsic.

Let's look at the UML of the flyweight pattern first, then we will look at an example to see how it works. Below is the UML for the flyweight design pattern:

 

  • The FlyweightFactory class is just an indexer that allows you to retrieve the flyweight object when given an index number, since you may have many flyweight objects in your application. 
  • The IFlyweight interface defines the methods and the properties required for the flyweight objects. The GetExtrinsicState method gets the extrinsic states and the ­intrinsicState variable holds the intrinsic states. 
  • The ConcreteFlyweight class is the actual flyweight object. The intrinsicState variable stores the information that are constant, while the GetExtrinsicState method calculates the extrinsic states on the fly.

Applying the UML of the flyweight pattern to our example of creating aliens of different shapes and colors gives us the following UML:

  • The AlienFactory class stores and retrieves different types of aliens using its GetAlien and SaveAlien methods. 
  • The IAlien interface defines the shape property as the intrinsic state and the GetColor method as the extrinsic state.
  • The LargeAlien and the LittleAlien classes are the flyweight objects where each has its own shape intrinsic state and ways of calculating the GetColor extrinsic state.

A comparison between the flyweight pattern and the prototype pattern shows some similarities in the UML, in that both use a manager to store and retrieve the objects in the collection. But there is a clear difference between the two. The prototype pattern is used to create new objects that are similar in nature (hence it's a creational pattern), while the flyweight pattern is used to allow the application to point to the same instance of the object to save memory (hence it's a structural pattern).

 

Below are the implementation code and the output of the example using the flyweight design pattern. Notice that the intrinsic states are stored in one place only to save memory while the extrinsic states are calculated on the fly:

public enum Color { Green, Red, Blue }

class Program
{
    static void Main(string[] args)
    {
        //create Aliens and store in factory
        AlienFactory factory = new AlienFactory();
        factory.SaveAlien(0, new LargeAlien());
        factory.SaveAlien(1, new LittleAlien());

        //now access the flyweight objects
        IAlien a = factory.GetAlien(0);
        IAlien b = factory.GetAlien(1);

        //show intrinsic states, all accessed in memory without calculations
        Console.WriteLine("Showing intrinsic states...");
        Console.WriteLine("Alien of type 0 is " + a.Shape);
        Console.WriteLine("Alien of type 1 is " + b.Shape);

        //show extrinsic states, need calculations
        Console.WriteLine("Showing extrinsic states...");
        Console.WriteLine("Alien of type 0 is " + a.GetColor(0).ToString());
        Console.WriteLine("Alien of type 0 is " + a.GetColor(1).ToString());
        Console.WriteLine("Alien of type 1 is " + b.GetColor(0).ToString());
        Console.WriteLine("Alien of type 1 is " + b.GetColor(1).ToString());
    }
}

public interface IAlien
{
    string Shape { get; }  //intrinsic state

    Color GetColor(int madLevel);  //extrinsic state
}

public class LargeAlien : IAlien
{
    private string shape = "Large Shape";  //intrinsic state

    string IAlien.Shape
    {
        get { return shape; }
    }

    Color IAlien.GetColor(int madLevel)   //extrinsic state
    {
        if (madLevel == 0)
            return Color.Green;
        else if (madLevel == 1)
            return Color.Red;
        else
            return Color.Blue;
    }
}

public class LittleAlien : IAlien
{
    private string shape = "Little Shape";  //intrinsic state

    string IAlien.Shape
    {
        get { return shape; }
    }

    Color IAlien.GetColor(int madLevel)   //extrinsic state
    {
        if (madLevel == 0)
            return Color.Red;
        else if (madLevel == 1)
            return Color.Blue;
        else
            return Color.Green;
    }
}

public class AlienFactory
{
    private Dictionary<int,> list = new Dictionary<int,>();

    public void SaveAlien(int index, IAlien alien)
    {
        list.Add(index, alien);
    }

    public IAlien GetAlien(int index)
    {
        return list[index];
    }
}</int,></int,>

Liked this article? You can see this and other great articles on design patterns here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

DevLake

United States United States
No Biography provided

Comments and Discussions

 
SuggestionWrong naming of class AlienFactory [modified] PinmemberRainerVoegtlin31-Jul-14 0:32 
Questionnice content but seems wrong example PinmemberMirani Ajay21-Mar-14 1:16 
QuestionThe URL of UML image is not avaiable Pinmembernhthai22071-May-13 0:05 
GeneralIn contect of String class PinmemberJava Experience30-Jan-13 18:14 
GeneralMy vote of 4 PinmemberRhuros4-May-11 2:28 
GeneralRe: My vote of 4 PinmemberImtiaz.Ahmed22-May-11 9:23 
GeneralTags Pinmemberalxxl26-Apr-11 4:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 4 May 2011
Article Copyright 2011 by DevLake
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid