Sunday, September 25, 2016

Flyweight Pattern

When to use –

Flyweight pattern can be used in scenarios where memory is major constraint. Flyweight pattern reuses already created similar objects and stores
them and creates new object only when no similar object found. So by doing this
it reduces number of new objects created and decrease memory usage. Flyweight
pattern uses sharing mechanism to support large number of objects efficiently.

Major components of Flyweight pattern –

Flyweight – This is an interface defines the members
of flyweight class.

//triangle object is not shared so
new object will be created everytime

IShape
triangle1 = shapeFactory.GetShape(ShapeType.Triangle);

triangle1.Draw(30);

IShape
triangle2 = shapeFactory.GetShape(ShapeType.Triangle);

triangle2.Draw(31);

Console.ReadLine();

}

}

Output –

As you can see in above example, Flyweight pattern uses flyweight
factory to create object and manage them. Flyweight factory creates objects and
store them, if object is already created it will return the existing object and if
not then it will create new object and return. Flyweight factory also manages unshared objects
which will be always created returned and never stored. This way flyweight enforces
reusability of existing object and reduce memory usage.

I hope this article helps you to know more about Flyweight
Pattern. Please leave your feedback in comments section below.