Flyweight Pattern

Used to improve performance when object instantiation is expensive and/or to reduce memory footprint.

We create a factory which stores already created objects. When an object is requested it first looks into its cache to see if the object was already created. If object exists, it returns, if not it creates and stores a new instance.

Objects must be immutable and every change of state must be performed in its factory.

Bricks:

  • interface defining operations that can performed on the object
  • concrete implementations of this interface
  • factory instantiating and caching objects

Example: