Open In App

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 state externally, typically within a Flyweight factory. This pattern is particularly useful when you need to create a significant number of similar objects and want to minimize the memory footprint.

Problem Statement

In many applications, you may need to create a large number of objects that have some common properties or characteristics. Without optimization, this can lead to excessive memory consumption because each object contains duplicated data for the common properties. Additionally, it may impact performance due to the overhead of creating and managing numerous objects.



Solution

The Flyweight pattern suggests separating the intrinsic state (shared among multiple objects) from the extrinsic state (varies between objects). The intrinsic state is stored externally, typically within a Flyweight factory, and the extrinsic state is provided by the client code when needed.

Key Components

  1. Flyweight Interface or Base Class: This defines the methods for accessing and manipulating the intrinsic state.
  2. Concrete Flyweight: Implementations of the Flyweight interface that store and manage the intrinsic state. They are typically lightweight and capable of being shared.
  3. Flyweight Factory: A factory class responsible for creating and managing flyweight objects. It ensures that flyweights are shared and reused when possible.

Use Cases

Example

Consider a text editor where each character in the document is represented as an object. If you have a large document, creating individual objects for each character can be memory-intensive. However, most characters share common properties like the font and size, which can be optimized to reduce memory usage.



Below is the implementation of a simplified example using characters in a text editor:




#include <iostream>
#include <unordered_map>
 
// Flyweight class
class Character {
public:
    Character(char intrinsicState) : m_intrinsicState(intrinsicState) {}
 
    void draw(int extrinsicState) {
        std::cout << "Drawing character '" << m_intrinsicState << "' at position " << extrinsicState << std::endl;
    }
 
private:
    char m_intrinsicState;
};
 
// Flyweight factory
class CharacterFactory {
public:
    Character* getCharacter(char key) {
        if (m_characters.find(key) == m_characters.end()) {
            m_characters[key] = new Character(key);
        }
        return m_characters[key];
    }
 
private:
    std::unordered_map<char, Character*> m_characters;
};
 
int main() {
    CharacterFactory characterFactory;
 
    // Extrinsic state
    int position = 0;
 
    // Drawing characters 'A', 'B', 'C' at different positions
    characterFactory.getCharacter('A')->draw(position++);
    characterFactory.getCharacter('B')->draw(position++);
    characterFactory.getCharacter('C')->draw(position++);
 
    return 0;
}

Output:

Drawing character ‘A’ at position 0
Drawing character ‘B’ at position 1
Drawing character ‘C’ at position 2

In this example, we have a Character class that represents a flyweight object.

In the main() function, we demonstrate how to use the flyweight objects. We create three characters (‘A’, ‘B’, ‘C’) at different positions and draw them on the screen.

Diagram Explaining the Flyweight Pattern

Flow diagram of flyweight pattern

In this diagram:

In practice, the Flyweight Factory is responsible for managing the sharing of flyweight objects, ensuring that multiple objects with the same intrinsic state are represented by a single shared instance. This helps minimize memory usage and improve performance, especially when dealing with a large number of similar objects.

Advantages of Flyweight Pattern in C++ Design Patterns

Here are the advantages of the Flyweight pattern in C++:

Disadvantages of Flyweight Pattern in C++ Design Patterns

Here are some potential disadvantages of using the Flyweight pattern in C++,

Uses of Flyweight Pattern

Here are some common uses of the Flyweight pattern in C++,


Article Tags :