![]() |
VOOZH | about |
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects.
The shared data typically consists of two types of properties:
Step 1: First, we must create a Flyweight object with intrinsic and extrinsic properties.
Explanation:
In this step, we created a `FlyweightDP` class which contains the constructor to initialize the `sharedData`(Intrinsic properties) and the `operation` method takes the `uniqueData` (Extrinsic properties) and logs a message combining shared and unique data.
Step 2: Create a `FlyweightFactory` class which is used to manage and reuse the shared data and properties efficiently.
Explanation:
In this step, we created a `FlyweightFactory` which contains a constructor to initialize an empty object called `data` to store the instances of `FlyweightDP` class. The `getData` method takes the `sharedData` as a parameter and checks whether a flyweight(object/instance of `FlyweightDP` class) with the given `sharedData` exists in the `data` object or not.
If it doesn't exists it create a new flyweight with that `sharedData` and add it to the `data` object and returns the flyweight associated with that `sharedData`. The `getFlyweightsCount` method returns the count of flyweights or instances of `FlyweightDP` class.
Step 3: Create an object for the `FlyweightFactory` class to understand the working of Flyweight design pattern.
Explanation:
In this step we created an object called `factory` for the `FlyweightFactory` class and invoked the `getData` method with the parameter 'A' which is stored in `flyweight1` and invoked the `operation` method with parameter '1'. We invoked the method `getData` with the parameter 'B' which is stored in `flyweight2` and invoked `operation` method with parameter '2'. We invoked the method `getData` with the parameter 'A' again. now it will be not added because it is already present in the object and invoked the operation method with parameter '3'.
Output:
Intrinsic Property: A, Extrinsic Property: 1
Intrinsic Property: B, Extrinsic Property: 2
Intrinsic Property: A, Extrinsic Property: 3
Number of flyweights created: 2
The Flyweight design pattern has serveral advantages including:
The Flyweight design pattern has some disadvantages in terms of:
1. When do we use Flyweight design pattern?
A. In software development, we may rely on the Flyweight pattern when we need to manage a large number of similar objects efficiently, especially when the objects share common intrinsic (immutable) properties that can be shared among multiple instances.
2. Can you provide an example of a real-world use case for the Flyweight pattern?
A. In a text editor, characters in a document can be represented using the Flyweight pattern. Fonts, sizes, and styles are shared (intrinsic) properties, while character positions are unique (extrinsic) properties.