Tuesday, November 06, 2007

* Patterns : Flyweight Structural Pattern

Flyweight Structural Pattern is used to manage large number of shared objects. They are maintained in a collection and same instances used whenever required. These objects have their own attributes/features but they can have a common feature also which can be externalized.

Consider a scenario where a picture has to be drawn which consists of large numbers of polygons of different colors. All polygons have number of sides property which is very specific to them but all of them have a common property called color which can be externalized. Also for same polygon type like 'Square',  number of sides remain same but color may change. Flyweight pattern helps in managing such kind of scenarios.


Polygon factory manages the collection of polygons. Each concrete polygon stores number of sides but the color property is taken at runtime. Same instance of polygon can be used to draw any number of times with different color.

The client code is following :

namespace FlyWeight
    public class Client
        PolygonFactory factory;
        public void Run()
            factory = new PolygonFactory();
            Polygon square = factory.GetPolygon("SQUARE");
            Polygon triangle = factory.GetPolygon("TRIANGLE");

Download source code : Flyweight Structural Pattern Source Code

No comments:

Post a Comment