Flyweight

Structural pattern

Flyweight is a pattern dedicated to building light objects by abstracting parts that can be reused and shared in order to create new objects when required, and reusing objects created by other instances, significantly reducing the amount of memory being used by the application.

This pattern is useful when resource optimization is fundamental, because it eliminates redundancy on objects with identical properties.

Flyweight pattern structure.
Flyweight pattern structure.

The components included in the pattern are:

  • Client: Object which triggers the execution.
  • FlyweightFactory: Factory for building the Flyweight objects.
  • Flyweight: It refers to the objects we want to reuse in order to create lighter objects.
Flyweight pattern sequence diagram
Flyweight pattern sequence diagram
  1. The client requests the Factory for the creation of a Flyweightobject.
  2. Before creating the object, the Factory checks if there's an identical object to the one being requested, if so, it returns the existing object; if not, it will create the new object and store it in a cache for further use.
  3. The Flyweight object is created or borrowed from the cache and returned to the client.

Real-world example

By implementing the Flyweight design pattern, we are going create an application for managing playlists. Some songs must be shared between various playlists, and some songs must have shared sections between them in order to save memory space.

Discover how the Flyweight pattern can help us solve this problem
Discover how the Flyweight pattern can help us solve this problem

About this book

Introduction to design patterns

Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:

See book
All rights reserved ©
Reactive programming
LinkedinYoutubeTwitterFacebook

© 2021, Copyright - Oscar Blancarte. All rights reserved.