The Flyweight Pattern is a structural design pattern that focuses on minimizing memory usage by sharing as much data as possible with other similar objects. This pattern is particularly useful when you have a large number of objects that share common state and can be represented by a smaller set of distinct objects. By reusing these shared objects, the Flyweight Pattern helps to reduce memory overhead and improve performance.
Consider an application that needs to display a large number of similar text elements on a screen, such as a word processor or a game with numerous identical characters. Each text element might have unique properties like position, color, and size, but they share the same font and style. Creating a new object for each text element would be memory-intensive.
The Flyweight Pattern suggests that you should separate the intrinsic state (which can be shared) from the extrinsic state (which cannot be shared). The intrinsic state is stored in the flyweight objects, while the extrinsic state is passed to the flyweight methods when needed. This way, multiple clients can share a single flyweight object without interfering with each other.
The Flyweight Pattern typically involves the following components:
Let's consider a word processor application where we need to display multiple text elements with different positions but the same font and style.
// Flyweight interface
class TextFlyweight {
constructor(font, style) {
this.font = font;
this.style = style;
}
render(position, color) {
console.log(`Rendering text at position ${position} with color ${color}, using font: ${this.font}, style: ${this.style}`);
}
}
// FlyweightFactory
class TextFlyweightFactory {
constructor() {
this.flyweights = {};
}
getFlyweight(font, style) {
const key = `${font}-${style}`;
if (!this.flyweights[key]) {
this.flyweights[key] = new TextFlyweight(font, style);
}
return this.flyweights[key];
}
}
// Client code
const factory = new TextFlyweightFactory();
const text1 = factory.getFlyweight('Arial', 'Bold');
text1.render({ x: 10, y: 20 }, 'red');
const text2 = factory.getFlyweight('Arial', 'Bold');
text2.render({ x: 30, y: 40 }, 'blue');
const text3 = factory.getFlyweight('Times New Roman', 'Italic');
text3.render({ x: 50, y: 60 }, 'green');
render method takes extrinsic state (position and color) as parameters.The Flyweight Pattern is an effective strategy for reducing memory usage in applications with a large number of similar objects. By sharing common data among multiple objects, it minimizes memory overhead and improves performance. This pattern is particularly useful in scenarios where creating new objects is expensive or when memory resources are limited.