Search⌘ K
AI Features

Flyweight Pattern

Explore the flyweight pattern to understand how it enables data sharing across many objects, reducing memory usage and improving performance. Learn to implement this structural pattern in JavaScript for coding interviews, focusing on real-world examples like formatters and caching.

What is the flyweight pattern?

It is a structural pattern that focuses on how related objects share data. It helps prevent repetitive code and increases efficiency when it comes to data sharing as well as conserving memory.

This pattern takes the common data structures/objects that are used by a lot of objects and stores them in an external object (flyweight) for sharing. You could say that it is used for caching purposes. So, the same data does not need to have separate copies for each object, instead, it is shared amongst all.

A flyweight is an independent object that can be used in multiple contexts simultaneously. It cannot be distinguished from the instances of objects that are not sharable. A flyweight object can consist of two states: ...