Problem

Using objects to define a system all the way down to the most specific level provides optimal flexibility, but we often find recurring, related object types at a low level. Creating and managing these objects is unacceptably expensive in terms of memory usage and performance.

Solution

Share objects to support many related objects efficiently.

Related Patterns

Discussion

Flyweight variations are stored in the repository of the application's Factory. Flyweight is generally only useful when the object overhead in a system reaches a critical point.

Examples

Storing each graphical glyph for text is an extremely bloated way to store that information. Instead, a commonly-known code for that glyph is stored. When we need to display that again, we pull the glyph corresponding to that code from the local Factory's repository.

Code

ASCII is a Flyweight for characters. The ASCIIchar class prints the internal values as an int and as a char, to represent the table of characters with a value.

class ASCIIchar{
private:
  int c; char ch;
public:
  ASCIIchar(int c){
    this.c = c;
    ch = c;
  }
  void print(){
    cout << (int)c << " " << ch << endl;
  }
}
ASCIIchar foo = new ASCIIchar(65);
ASCIIchar bar = new ASCIIchar(110);

int main(){
  foo->print();
  bar->print();
}