Flyweight Design Pattern
Last Updated :
03 Jul, 2024
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.
Important Topics for the Flyweight Design Pattern
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:
- Flyweight Interface/Class:
- Defines the interface through which flyweight objects can receive and act on extrinsic state.
- 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.
- 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.
- 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.
Please Login to comment...