Wednesday, June 1, 2016

Flyweight Pattern example java

Flyweight reduces the cost of creating and manipulating a large number of similar objects.Flyweight is used when there is a need to create large number of objects which are in similar nature.Large number of objects consumes high memory and flyweight design pattern gives a solution to reduce the load on memory by sharing objects.It is achieved by isolating object properties into two types intrinsic and extrinsic .

Intrinsic and Extrinsic State:

Create only 25 objects for mapping every unique characters. these 26 objects will have intrinsic state as its character.that is object '"a" will have state as character "a" .then what happens to color ,font and size? those are the extrinsic state and will be passed by client code.26 objects will be in store;client code will get the needed character/object and pass the extrinsic state to it with respect to the context.with respect to context means '''a" in first line may com in red color and same character may com in blue in different line.

When to use Flyweight Design Pattern:


  • Need to create large number of objects.
  • Because of the large number when memory cost is a constraint.
  • When most of the object attribute can be made external and shared.
  • Its better when extrinsic state can be computed rather than stored.

No comments: