Click here to Skip to main content
15,885,216 members
Articles / Protected
Article

Flyweight Pattern

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
11 Oct 2013CPOL3 min read 6.2K   1  
The flyweight pattern is used whenever you have large amount of small objects that share common information. The use of the pattern reduces the

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

The flyweight pattern is used whenever you have large amount of small objects
that share common information.
The use of the pattern reduces the storage of those objects.
The flyweight distinguishes between inner state (sometime called intrinsic state)
and outer state (sometime called extrinsic state) of the object.
The inner state can be shared by the objects and therefore minimize the amount
of storage needed by the objects.
The outer state can be computed or stored outside the objects and are given to
the objects whenever it's needed.
For a UML diagram of the pattern go to dofactory site.

Flyweight C# Example
Lets look at an example for the use of flyweight pattern:

    #region Helper

 

    public enum eNumbers

    {

        One,

        Two,

        Three,

        // .. and so on with every number

    }

 

    #endregion

 

    #region The Flyweight Factory

 

    public class NumbersFactory

    {

        #region Members

 

        private Dictionary<eNumbers, Number> _numbers =

            new Dictionary<eNumbers, Number>();

 

        #endregion

 

        #region Methods

 

        public Number GetNumber(eNumbers number)

        {

            if (!_numbers.ContainsKey(number))

            {

                switch (number)

                {

                    case (eNumbers.One):

                        {

                            _numbers.Add(number, new One());

                            break;

                        }

                    case (eNumbers.Two):

                        {

                            _numbers.Add(number, new Two());

                            break;

                        }

                    case (eNumbers.Three):

                        {

                            _numbers.Add(number, new Three());

                            break;

                        }

                        // ... and so on with every number

                    default:

                        {

                            break;

                        }

                }

            }

            return _numbers[number];

        }

 

        #endregion

    }

 

    #endregion

 

    #region The Flyweight

 

    public abstract class Number

    {

        #region Members

 

        protected int _number;

        protected string _numberName;

        protected int _numberSize;

 

        #endregion

 

        #region Methods

 

        public abstract void WriteNumber(int numberSize);

 

        #endregion

    }

 

    #endregion

 

    #region The Flyweight Concrete

 

    public class One : Number

    {

        #region Ctor

 

        public One()

        {

            this._number = 1;

            this._numberName = "One";

        }

 

        #endregion

 

        #region Methods

 

        public override void WriteNumber(int numberSize)

        {

            this._numberSize = numberSize;

            Console.WriteLine(string.Format("{0} is size {1}",

                _numberName, _numberSize));

        }

 

        #endregion

    }

 

    public class Two : Number

    {

        #region Ctor

 

        public Two()

        {

            this._number = 2;

            this._numberName = "Two";

        }

 

        #endregion

 

        #region Methods

 

        public override void WriteNumber(int numberSize)

        {

            this._numberSize = numberSize;

            Console.WriteLine(string.Format("{0} is size {1}",

                _numberName, _numberSize));

        }

 

        #endregion

    }

 

    public class Three : Number

    {  

        #region Ctor

 

        public Three()

        {

            this._number = 3;

            this._numberName = "Three";

        }

 

        #endregion

 

        #region Methods

 

        public override void WriteNumber(int numberSize)

        {

            this._numberSize = numberSize;

            Console.WriteLine(string.Format("{0} is size {1}",

                _numberName, _numberSize));

        }

 

        #endregion

    }

 

    // ... Four, Five and so on

 

    #endregion

The example include 3 parts - the flyweight factory (NumberFactory), the flyweight
itself (Number) and flyweight concretes (One, Two, Three). You can see that lazy loading
is used in the factory. Whenever a number is needed and isn't in the factory I build it and
then return it in the GetNumber method.

Summary
To sum up, use the flyweight when you have a large amount of objects that
consume large amount of memory. Also use the pattern when you have groups of
objects that share common state.
From my experience, the pattern is rarely used. Even though, you should know the
pattern in order to use it when it is needed

This article was originally posted at http://wiki.asp.net/page.aspx/500/flyweight-pattern

License

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


Written By
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
This is a Collaborative Group

754 members

Comments and Discussions

 
-- There are no messages in this forum --