Wednesday 16 September 2015

Flyweight Pattern - A Structural design pattern

To reuse the object those are already created.

1. Reuse the object that already existing (earlier created and stored)
2. Create new object when no matching object is found.

This can be used to reduce memory requirements and substantiation time and related costs (object creational cost).

Similarities between objects are stored inside of the objects (intrinsic), and differences are moved outside of the objects and placed in client code (extrinsic).

Advantages
It reduces the number of objects.
It reduces the amount of memory and storage devices required if the objects are persisted.

Usage
When an application uses number of objects
When the storage cost is high because of the quantity of objects.
When the application does not depend on object identity.

Flyweight Pattern Example in JDK
All the wrapper classes valueOf() method uses cached objects showing use of Flyweight design pattern.

The best example is Java String class String Pool implementation.

Real Life Examples
Web browser
Modern web browsers use this technique to prevent loading same images twice. When browser loads a web page, it traverses through all images on that page. Browser loads all new images from Internet and places them the internal cache. For already loaded images, a flyweight object is created, which has some unique data like position within the page, but everything else is referenced to the cached one.

Game of war

A game of war, were there is a large number of soldier objects; a soldier object maintain the graphical representation of a soldier, soldier behaviour such as motion, and firing weapons, in addition soldiers health and location on the war terrain. Creating a large number of soldier objects is a necessity however it would incur a huge memory cost. Note that although the representation and behaviour of a soldier is the same their health and location can vary greatly.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...