Open In App

Flyweight Design Pattern – JavaScript Design Pattern

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Intrinsic properties: The properties that do not change over time while shared among related objects are called Intrinsic properties
  • Extrinsic properties: The properties that are unique to every, object and cannot be shared are called extrinsic properties.

Implementation of Flyweight Design Pattern in JavaScript:

Step 1: First, we must create a Flyweight object with intrinsic and extrinsic properties.

Javascript




class FlyweightDP {
  constructor(sharedData) {
    this.sharedData = sharedData;
  }
  operation(uniqueData) {
    console.log(`Intrinsic Property: ${this.sharedData}, Extrinsic Property: ${uniqueData}`);
  }
}


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.

Javascript




class FlyweightFactory {
  constructor() {
    this.data = {};
  }
  getData(sharedData) {
    if (!this.data[sharedData]) {
      this.data[sharedData] = new FlyweightDP(sharedData);
    }
    return this.data[sharedData];
  }
  getFlyweightsCount() {
    return Object.keys(this.data).length;
  }
}


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.

Javascript




const factory = new FlyweightFactory();
const flyweight1 = factory.getData('A');
flyweight1.operation('1');
const flyweight2 = factory.getData('B');
flyweight2.operation('2');
const flyweight3 = factory.getData('A');
flyweight3.operation('3');
console.log(`Number of flyweights created: ${factory.getFlyweightsCount()}`);


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

Diagrammatic Representation:

Picture1

Flyweight Design Pattern

Advantages of Flyweight Design Pattern:

The Flyweight design pattern has serveral advantages including:

  1. Memory Efficiency: The Flyweight design pattern reduces the memory usage by allowing related objects to share the common state.
  2. Performance Improvement: The Flyweight design pattern improves the performance in terms of processing speed and initialization time.
  3. Resource utilization: The Flyweight design pattern allows efficient use of resources by minimizing the number of instances required to represent a similar object.
  4. Reduced Redundancy: The Flyweight design pattern helps to reduce the redundant code by extracting the common state.

Disadvantages of Flyweight Design Pattern:

The Flyweight design pattern has some disadvantages in terms of:

  1. Dependency on a Factory: The Flyweight design pattern often relies on a factory for creating flyweight objects, introducing a dependency on this factory.
  2. Increased Complexity: Implementing the Flyweight design pattern can introduce additional complexity to the codebase, especially if the logic for managing shared and unique states is intricate.

FAQ:

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.



Previous Article
Next Article

Similar Reads

Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Flyweight Pattern | C++ Design Patterns
A flyweight pattern is a structural design pattern used to optimize memory usage and performance when dealing with a large number of objects that share some common characteristics. It achieves this by separating an object's intrinsic state (shared among multiple objects) from its extrinsic state (unique to each object) and storing the intrinsic sta
9 min read
Flyweight Method Design Pattern in Java
A flyweight design pattern or flyweight method is defined as a structural pattern that is used to minimize memory usage or computational expenses by sharing as much as possible with other similar objects. The key idea behind the Flyweight pattern is to use shared objects to support large numbers of fine-grained objects efficiently. Important Topics
9 min read
Flyweight Design Pattern
Flyweight pattern is one of the structural design patterns as this pattern provides ways to decrease object count thus improving application required objects structure. Flyweight pattern is used when we need to create a large number of similar objects (say 105). One important feature of flyweight objects is that they are immutable. This means that
7 min read
Flyweight Method - Python Design Patterns
Flyweight method is a Structural Design Pattern that focus on minimizing the number of objects that are required by the program at the run-time. Basically, it creates a Flyweight object which is shared by multiple contexts. It is created in such a fashion that you can not distinguish between an object and a Flyweight Object. One important feature o
5 min read
Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read