Monday, April 4, 2011

Flyweight pattern

Situation:
You have too many instances of a certain type and you are in desperate need of reducing the number of instances.

Flyweight pattern
You know that an object is a combination of both state and behaviour. As behaviours are attached to the class of the object rather than storing in the object itself (so that each object need not have a separate version of methods), the memory occupied by an object is proportional to the amount of state information stored by the object. Assume that in a text document, you represent each character as an object. In that case, if the document is lengthy, you will end up having too many objects. Flyweight pattern addresses this issue by decreasing the number of state information you store in the object. Instead of storing them as instance variables, pass the other state information as parameters to the methods.
E.g.
class MyCharacter {
  Font f;

  public MyCharacter(Font f) {
    this.f = f;
  }

  public void display(char c) {
    // Determine how to display the character in the specified font.
  }
}
Here, it is appropriate to think of character c itself having the details of its font. However, in that case, each character will have the same information in most of the cases and you might end up having so many objects in memory. Instead you have moved the font specific part alone to a separate class and now you can have a single instance for each type of Font and you need not store each character as a separate object thereby optimizing memory.

Advantage:
1. You can optimize memory.

Disadvantage:
1. It assumes that you are not special casing any of the objects, and all objects will behave identically.

No comments:

Post a Comment