codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🎭

Design Patterns

17 / 100 topics
11Introduction to Structural Patterns12Adapter Pattern13Bridge Pattern14Composite Pattern15Decorator Pattern16Facade Pattern17Flyweight Pattern18Proxy Pattern32Practical Exercises for Structural Patterns
Tutorials/Design Patterns/Flyweight Pattern
🎭Design Patterns

Flyweight Pattern

Updated 2026-04-20
3 min read

Introduction

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.

Problem

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.

Solution

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.

Structure

The Flyweight Pattern typically involves the following components:

  • Flyweight: Declares an interface through which flyweights can receive and act on extrinsic state.
  • ConcreteFlyweight: Implements the Flyweight interface and adds storage for intrinsic state. ConcreteFlyweight objects must be sharable. Any state it stores must be immutable; otherwise, different clients could alter its state.
  • UnsharedConcreteFlyweight (optional): Not all flyweights need to be shared. The UnsharedConcreteFlyweight class can implement the Flyweight interface when it makes sense to do so.
  • FlyweightFactory: Creates and manages flyweight objects. Ensures that flyweights are shared properly without creating unnecessary instances.

Real-World Example

Let's consider a word processor application where we need to display multiple text elements with different positions but the same font and style.

Code Implementation

// 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');

Explanation

  1. TextFlyweight: Represents the flyweight object that holds intrinsic state (font and style). The render method takes extrinsic state (position and color) as parameters.
  2. TextFlyweightFactory: Manages the creation and sharing of flyweight objects. It uses a dictionary to store existing flyweights based on their key, which is a combination of font and style.
  3. Client Code: Demonstrates how clients request flyweight objects from the factory and use them to render text with different positions and colors.

Best Practices

  1. Identify Shared State: Determine which parts of the object's state can be shared among multiple instances. These are the intrinsic states.
  2. Separate Intrinsic and Extrinsic States: Clearly distinguish between intrinsic (shared) and extrinsic (unique) states in your design.
  3. Use a Factory for Management: Implement a factory to manage flyweight objects efficiently, ensuring that they are reused when possible.
  4. Immutable State: Ensure that the intrinsic state of flyweight objects is immutable to prevent unintended side effects from shared instances.

Conclusion

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.


PreviousFacade PatternNext Proxy Pattern

Recommended Gear

Facade PatternProxy Pattern