Flyweight | Cheat Sheet

Structural Pattern — Design Patterns Series

Flyweight is also known as Cache and often found in the computer gaming section when sharing various GUI elements in order to save memory. It is defined by sharing fine-grained objects to efficiently deploy and reuse them in a large number.

Sometimes there may be runtime penalties associated with transferring, or locating. But these are offset by memory savings.

Real-life examples

  • Cache
  • Used in computer games when sharing GUI elements
  • For Special Case Objects

Meaning

  • Sharing fine-grained objects to efficiently deploy and reuse them in large numbers

Applicability (suitable if …)

All of the following points apply in one system:

  • Memory requirements are too high due to numerous objects used
  • Object state can be made extrinsic
  • Many groups of objects can be replaced by few shared objects after the extrinsic condition is removed
  • The application does not depend on the object identity

Assets and Drawbacks

  • There may be runtime penalties associated with transferring, locating, and/or computing the extrinsic state
  • Runtime penalties are offset by memory savings (reduction in total number of instances resulting from sharing, extent of intrinsic state per object, computation, or storage of extrinsic state)

Example

For this example I was inspired by another tutorial.

With different brushes you can write or paint with varying thicknesses and colors. Brushes, which have already been used, can be reused later.

First of all, you need to define an enum for different thicknesses:

After that, you need to define the interface for the brush, which at the same time acts as Flyweight:

Next, you need to define different pens with different thicknesses:

Then, you need a place for creating the instances for different brushes: a Factory.

At last, the client needs to instantiate different kinds of brushes and draw some text in different colors with it:

Conclusion

Design Patterns are an important resource and base knowledge for every developer — they are very helpful for solving programmatic problems, help with consistent communication with other developers about system design, and serve as a significant introduction into object composition (besides inheritance) and dependency inversion.

Structural Patterns are indispensable when objects are combined to create new functionalities. Comprehensive structures are built by using compositions of classes and objects. This provides flexibility due to variable composition structure depending on the runtime. One thus achieves an increase in efficiency and consistency.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store