Flyweight
Last updated
Last updated
Flyweight is a structural design pattern that lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects instead of keeping all of the data in each object.
The Flyweight design pattern is a structural pattern used to minimize memory usage and improve performance by sharing as much data as possible with similar objects.
It's particularly useful when dealing with a large number of similar objects that could share common properties.
In JavaScript, you can implement the Flyweight pattern to optimize memory usage, especially when dealing with large collections of objects with shared characteristics.
In this example, FlyweightFactory
manages the creation and retrieval of flyweight objects. Each flyweight object, represented by the class Flyweight
, contains intrinsic state (data that can be shared) and extrinsic state (unique data specific to each object). The factory ensures that if a flyweight with a particular key already exists, it returns the existing one instead of creating a new one.
This pattern is useful when you have a large number of objects that share common data, such as text formatting options in a document editor or graphical elements in a game. By sharing common data, you can significantly reduce memory usage and improve performance.