The Wayback Machine - https://web.archive.org/web/20240913230706/https://www.geeksforgeeks.org/flyweight-design-pattern/
Open In App

Flyweight Design Pattern

Last Updated : 03 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Flyweight design pattern is a structural pattern that focuses on optimizing memory usage by sharing a common state among multiple objects. It aims to reduce the number of objects created and to decrease memory footprint, particularly useful when dealing with a large number of similar objects.

What is Flyweight Design Pattern?

The Flyweight design pattern is a structural pattern that aims to minimize memory usage and improve performance by sharing objects that have similar or identical states. It is particularly useful when dealing with many objects that can be grouped into shared flyweight objects, reducing the overall memory footprint.

Some key concepts of flyweight design pattern:

  • Shared State: Objects are divided into intrinsic (shared) state and extrinsic (context-dependent) state. The intrinsic state is shared among multiple objects, while the extrinsic state can vary and is passed to the flyweight objects as needed.
  • Object Reuse: Instead of creating new objects each time they are needed, Flyweight objects are reused from a pool of existing objects. This reduces the amount of memory used and improves performance.
  • Factory for Flyweights: A factory class manages the creation and reuse of flyweight objects. It ensures that clients get a shared flyweight object when they request one, or it creates a new one only if necessary.

Real-World Example of Flyweight Design Pattern

Imagine a text editor where each character on the screen needs to be displayed with a specific font, size, and style. Instead of creating a new object for every character with the same formatting, the text editor uses a shared pool of character objects (flyweights) that store common formatting details. This approach saves memory and improves performance by reusing objects, ensuring efficient handling of large amounts of text with varying formatting needs.

Components of Flyweight Design Pattern

The Flyweight design pattern typically consists of the following components:

  1. Flyweight Interface/Class:
    • Defines the interface through which flyweight objects can receive and act on extrinsic state.
  2. Concrete Flyweight Classes:
    • Implements the Flyweight interface and represents objects that can be shared.
    • Stores intrinsic state (state that can be shared) and provides methods to manipulate intrinsic state if needed.
  3. Flyweight Factory:
    • Manages a pool of flyweight objects.
    • Provides methods for clients to retrieve or create flyweight objects.
    • Ensures flyweight objects are shared appropriately to maximize reusability.
  4. Client:
    • Uses flyweight objects to perform operations.
    • Maintains or passes extrinsic state to flyweight objects when needed.
    • Does not manage the lifecycle of flyweight objects directly but interacts with them via the factory.

Example Implementation of Flyweight Design Pattern

Below is the problem statement to understand flyweight design pattern:

Imagine a graphical user interface (GUI) application where multiple icons of different types (e.g., file icons, folder icons) need to be displayed on a screen. Each icon type has a specific appearance and behavior, such as different images and positions on the screen. However, displaying numerous icons of the same type can consume significant memory if each icon object stores its unique properties independently.

How Flyweight Design Pattern will help in this problem situation:

  • The Flyweight design pattern can optimize memory usage by sharing common parts of the icons (intrinsic state), such as the image and basic properties (like size and color), among multiple icon instances.
  • Each icon instance then stores only its unique properties (extrinsic state), such as its position on the screen.
  • This approach reduces the memory footprint and enhances performance, especially when dealing with a large number of similar objects.

Component wise code of flyweight design pattern:

Below is the component wise code of flyweight design pattern:

1. Flyweight Interface:

Java
// Flyweight interface
public interface Icon {
    void draw(int x, int y);  // Method to draw the icon at given coordinates
}

2. Concrete Flyweight Classes

Java
// Concrete Flyweight class representing a File Icon
public class FileIcon implements Icon {
    private String type;  // Intrinsic state: type of file icon (e.g., document, image)
    private Image image;  // Intrinsic state: image specific to the file icon

    public FileIcon(String type, Image image) {
        this.type = type;
        this.image = image;
    }

    @Override
    public void draw(int x, int y) {
        // Draw logic specific to file icon using intrinsic state (image)
        System.out.println("Drawing " + type + " icon at position (" + x + ", " + y + ")");
    }
}

// Concrete Flyweight class representing a Folder Icon
public class FolderIcon implements Icon {
    private String color;  // Intrinsic state: color of the folder icon
    private Image image;   // Intrinsic state: image specific to the folder icon

    public FolderIcon(String color, Image image) {
        this.color = color;
        this.image = image;
    }

    @Override
    public void draw(int x, int y) {
        // Draw logic specific to folder icon using intrinsic state (image)
        System.out.println("Drawing folder icon with color " + color + " at position (" + x + ", " + y + ")");
    }
}

3. Flyweight Factory

Java
import java.util.HashMap;
import java.util.Map;

// Flyweight factory to manage creation and retrieval of flyweight objects
public class IconFactory {
    private Map<String, Icon> iconCache = new HashMap<>();

    public Icon getIcon(String key) {
        // Check if the icon already exists in the cache
        if (iconCache.containsKey(key)) {
            return iconCache.get(key);
        } else {
            // Create a new icon based on the key (type of icon)
            Icon icon;
            if (key.equals("file")) {
                icon = new FileIcon("document", loadImage("document.png"));
            } else if (key.equals("folder")) {
                icon = new FolderIcon("blue", loadImage("folder.png"));
            } else {
                throw new IllegalArgumentException("Unsupported icon type: " + key);
            }
            // Store the created icon in the cache
            iconCache.put(key, icon);
            return icon;
        }
    }

    // Simulated method to load image based on filename
    private Image loadImage(String filename) {
        // Load image from file system or resource
        // Here, returning a dummy Image object
        return new Image(filename);
    }
}

4. Client Code

Java
// Client code to use the flyweight objects (icons)
public class Client {
    public static void main(String[] args) {
        IconFactory iconFactory = new IconFactory();

        // Draw file icons at different positions
        Icon fileIcon1 = iconFactory.getIcon("file");
        fileIcon1.draw(100, 100);

        Icon fileIcon2 = iconFactory.getIcon("file");
        fileIcon2.draw(150, 150);

        // Draw folder icons at different positions
        Icon folderIcon1 = iconFactory.getIcon("folder");
        folderIcon1.draw(200, 200);

        Icon folderIcon2 = iconFactory.getIcon("folder");
        folderIcon2.draw(250, 250);
    }
}

Complete code of the flyweight design pattern:

Java
import java.util.HashMap;
import java.util.Map;

// Flyweight interface
interface Icon {
    void draw(int x, int y);  // Method to draw the icon at given coordinates
}

// Concrete Flyweight class representing a File Icon
class FileIcon implements Icon {
    private String type;  // Intrinsic state: type of file icon
    private String imageName;  // Intrinsic state: image name specific to the file icon

    public FileIcon(String type, String imageName) {
        this.type = type;
        this.imageName = imageName;
    }

    @Override
    public void draw(int x, int y) {
        // Simulated logic to load and draw image
        System.out.println("Drawing " + type + " icon with image " + imageName + " at position (" + x + ", " + y + ")");
    }
}

// Concrete Flyweight class representing a Folder Icon
class FolderIcon implements Icon {
    private String color;  // Intrinsic state: color of the folder icon
    private String imageName;  // Intrinsic state: image name specific to the folder icon

    public FolderIcon(String color, String imageName) {
        this.color = color;
        this.imageName = imageName;
    }

    @Override
    public void draw(int x, int y) {
        // Simulated logic to load and draw image
        System.out.println("Drawing folder icon with color " + color + " and image " + imageName + " at position (" + x + ", " + y + ")");
    }
}

// Flyweight factory to manage creation and retrieval of flyweight objects
class IconFactory {
    private Map<String, Icon> iconCache = new HashMap<>();

    public Icon getIcon(String key) {
        // Check if the icon already exists in the cache
        if (iconCache.containsKey(key)) {
            return iconCache.get(key);
        } else {
            // Create a new icon based on the key (type of icon)
            Icon icon;
            if (key.equals("file")) {
                icon = new FileIcon("document", "document.png");
            } else if (key.equals("folder")) {
                icon = new FolderIcon("blue", "folder.png");
            } else {
                throw new IllegalArgumentException("Unsupported icon type: " + key);
            }
            // Store the created icon in the cache
            iconCache.put(key, icon);
            return icon;
        }
    }
}

// Client code to use the flyweight objects (icons)
public class Client {
    public static void main(String[] args) {
        IconFactory iconFactory = new IconFactory();

        // Draw file icons at different positions
        Icon fileIcon1 = iconFactory.getIcon("file");
        fileIcon1.draw(100, 100);

        Icon fileIcon2 = iconFactory.getIcon("file");
        fileIcon2.draw(150, 150);

        // Draw folder icons at different positions
        Icon folderIcon1 = iconFactory.getIcon("folder");
        folderIcon1.draw(200, 200);

        Icon folderIcon2 = iconFactory.getIcon("folder");
        folderIcon2.draw(250, 250);
    }
}


Output
Drawing document icon with image document.png at position (100, 100)
Drawing document icon with image document.png at position (150, 150)
Drawing folder icon with color blue and image folder.png at po...

Application of Flyweight Design Pattern

The Flyweight design pattern is applicable in scenarios where:

  • Large Number of Objects: When your application uses a large number of objects that could benefit from sharing common state (intrinsic state), such as text characters in a document, graphical elements in a user interface, or any kind of repeated data.
  • Memory Efficiency: It helps in reducing memory usage by sharing common data across multiple objects instead of storing it redundantly in each object instance.
  • Performance Optimization: By reducing the number of objects and the amount of memory they consume, the Flyweight pattern can improve performance, especially in applications that handle large datasets or require frequent creation and destruction of objects.
  • Immutable Objects: It works well with immutable objects where the intrinsic state (shared state) remains constant throughout the object’s lifetime.

When to use Flyweight Design Pattern

  • When you need to create a large number of similar objects: For example, if you need to create thousands of graphical objects (like icons, buttons) that share common properties (like image, color) but have different positions or other variable attributes.
  • When memory consumption is a concern: If your application is memory-intensive and creating multiple instances of similar objects would consume significant memory, the Flyweight pattern can help in reducing the memory footprint by sharing common state.
  • When performance optimization is needed: By reducing the number of objects, the pattern can improve performance by reducing the overhead associated with object creation, destruction, and garbage collection.

When not to use Flyweight Design Pattern

  • When objects have unique intrinsic states: If each object instance requires a unique set of intrinsic state that cannot be shared with other objects, applying the Flyweight pattern may not provide significant benefits.
  • When the overhead of implementing the pattern outweighs the benefits: If the number of objects is relatively small or the shared state is minimal, the complexity introduced by the Flyweight pattern may not justify its implementation.
  • When mutable objects are involved: The Flyweight pattern is best suited for immutable objects or objects whose intrinsic state does not change once initialized. If objects frequently change their intrinsic state, managing shared state can become complex and error-prone.
  • When the application does not have performance or memory constraints: If memory usage and performance are not critical concerns for your application, implementing the Flyweight pattern may add unnecessary complexity without significant benefits.

Conclusion

The Flyweight design pattern is valuable in situations where memory usage and performance optimization are crucial, especially when dealing with large numbers of similar objects. It facilitates efficient sharing of common state among multiple objects, thereby reducing memory footprint and improving performance. However, careful consideration should be given to the nature of objects, their state, and the overall design complexity before applying the Flyweight pattern.





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 Design Pattern - JavaScript Design Pattern
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. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 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 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
Difference Between Builder Design Pattern and Factory Design Pattern
Design patterns provide proven solutions to common problems in software design. The Builder and Factory patterns are two popular creational design patterns. The Builder pattern constructs complex objects step by step. In contrast, the Factory pattern creates objects without specifying their exact class. Both patterns streamline object creation but
7 min read
Why is Singleton Design Pattern is Considered an Anti-pattern?
Let us explore why the Singleton pattern, a popular way to ensure only one instance of a class exists, is now seen as problematic in software development. In this article, we will discuss drawbacks such as tight coupling between components, difficulty in unit testing, and issues with scalability in larger applications. Important Topics for Singleto
8 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
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
Design Patterns Cheat Sheet - When to Use Which Design Pattern?
In system design, selecting the right design pattern is related to choosing the right tool for the job. It's essential for crafting scalable, maintainable, and efficient systems. Yet, among a lot of options, the decision can be difficult. This Design Patterns Cheat Sheet serves as a guide, helping you on the path toward optimal design pattern selec
7 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 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
Difference Between Bridge Pattern and Adapter Pattern
The Bridge Pattern and the Adapter Pattern are structural design patterns in object-oriented software development that primarily target the flexibility and reusability of a design. These two patterns have different roles and are used in different scenarios to solve specific design issues. Important Topics for Bridge Pattern vs Adapter Pattern What
5 min read
Difference between Strategy pattern and Command pattern
In software design, patterns provide reusable solutions to common problems. The Strategy and Command patterns are two important behavioral design patterns. The Strategy pattern allows the selection of an algorithm at runtime. The Command pattern encapsulates a request as an object. Understanding the differences between these patterns is crucial for
6 min read
Strangler Pattern in Micro-services | System Design
The Strangler pattern is an architectural approach employed during the migration from a monolithic application to a microservices-based architecture. It derives its name from the way a vine slowly strangles a tree, gradually replacing its growth. Similarly, the Strangler pattern involves replacing parts of a monolithic application with microservice
4 min read
SAGA Design Pattern
SAGA pattern is a design pattern that is a long-lived sequence of smaller transactions. This pattern is used to manage and maintain data consistency across multiple microservices. Each transaction is executed by a single service, and the state changes are broadcasted to other services involved in the Saga. It helps to maintain data consistency by p
7 min read
10 Best Python Design Pattern Books for Beginners to Advanced
Imagine you're building different types of furniture using the same basic materials (like wood, screws, and nails). Instead of starting from scratch every time, you create templates or instructions for making specific types of furniture. These templates tell you what pieces to use, how to assemble them, and how to add unique features. In software p
4 min read
Abstract Factory Pattern | C++ Design Patterns
Abstract Factory Pattern is a creational design pattern used in object-oriented programming. It provides an interface for creating families of related or dependent objects without specifying their concrete classes. This pattern is a way to encapsulate the creation of objects and ensure that they are compatible and properly configured. In this artic
6 min read
Abstract Factory Pattern | JavaScript Design Patterns
Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface to create objects. Important Topics for the Abstr
6 min read
Bridge Method | JavaScript Design Pattern
In software design, as systems grow and evolve, the complexity of their components can increase exponentially. This complexity often arises from the intertwining of different functionalities and features, making the system rigid, less maintainable, and harder to scale. The Bridge design pattern emerges as a solution to this problem, offering a way
9 min read
Proxy Pattern | C++ Design Patterns
Design Patterns are an essential part of software engineering, offering proven solutions to common problems encountered during software development. One such pattern is the Proxy Pattern. The Proxy Pattern is a structural design pattern that provides a surrogate or placeholder for another object, allowing you to control access to it. This pattern c
7 min read
Introduction to Decorator Pattern in C++ | Design Patterns
The Decorator Pattern is a structural design pattern in software engineering that enables the dynamic addition of new behaviors or responsibilities to individual objects without altering their underlying class structure. It achieves this by creating a set of decorator classes that are used to wrap concrete components, which represent the core funct
12 min read
Memento Method - JavaScript Design Pattern
A behavioral design pattern in JavaScript called Memento focuses on externalizing and capturing an object's internal state so that it can later be restored. When you need to add features like undo/redo functionality, history tracking, or reverting an item to a former state, this pattern is quite helpful. Important Topics for the Memento MethodUnder
6 min read
Prototype Pattern | C++ Design Patterns
When designing software, it's crucial to make it efficient, easy to reuse, and simple to maintain. One way to achieve these goals is by using design patterns, and one such pattern is the Prototype Pattern. In this article, we'll explore the Prototype Design Pattern in the context of C++. Important Topics for the Prototype Pattern in C++ Design Patt
5 min read
Singleton Pattern | C++ Design Patterns
A singleton pattern is a design pattern that ensures that only one instance of a class can exist in the entire program. This means that if you try to create another instance of the class, it will return the same instance that was created earlier. The Singleton pattern is useful when we need to have only one instance of a class, for example, a singl
11 min read
Visitor design pattern
Visitor design pattern is one of the behavioral design patterns. It is used when we have to perform an operation on a group of similar kind of Objects. With the help of visitor pattern, we can move the operational logic from the objects to another class. The visitor pattern consists of two parts: a method called Visit() which is implemented by the
5 min read
Article Tags :