# Flyweight: Sharing Objects to Reduce Memory Usage

As applications grow, they often need to create and manage large numbers of objects. Some of these objects contain information that is unique to each instance, while other information is repeated across thousands of instances.

Consider a ticket-management application with a busy activity feed. Every time a ticket is created, assigned, updated or commented on, the system records an activity entry.

Each entry contains information such as the ticket reference, the person who performed the action and the time it occurred. However, it also needs presentation information: an event label, an icon, a colour and a description template.

The presentation information is not unique to every activity. Every ticket creation event uses the same presentation rules, as does every assignment event.

Creating a separate presentation object for every activity would mean repeatedly allocating objects containing identical information.

Could we share that repeated information instead?

The Flyweight pattern addresses this problem by allowing multiple objects to share common state rather than storing duplicate information in every instance.

In this article, we will explore the pattern using our ticket-management application, implement it in C# and examine when sharing objects is worth the additional complexity.

What is the Flyweight pattern?

The Flyweight pattern is a structural design pattern that reduces memory consumption by sharing objects containing repeated state.

The central idea is to identify which parts of an object's state are identical across multiple instances and which parts are specific to each instance.

These are known as:

\- Intrinsic state: Information that is shared between objects because it does not depend on the individual object's context.

\- Extrinsic state: Information that varies between objects and must be supplied by the client or stored in a separate context.

Instead of creating a complete object containing both types of state every time, the Flyweight pattern extracts the intrinsic state into a shared object. The extrinsic state remains with the individual object or is passed to the shared object when needed.

This allows many objects to reuse a smaller collection of shared instances.

For example, a ticket activity feed might contain 100,000 activity records but only four activity types:

\- Ticket created.

\- Ticket assigned.

\- Ticket status changed.

\- Comment added.

Rather than allocating 100,000 separate presentation-style objects, we can share just four Flyweight objects.

The 100,000 activity records still exist. What changes is that the repeated presentation metadata is no longer duplicated for every record.

Understanding the participants

The Flyweight pattern involves several participants.

Participant| Responsibility

Flyweight| Defines how shared state is represented and used.

Concrete Flyweight| Stores the intrinsic state that can be shared across multiple objects.

Flyweight Factory| Creates or retrieves existing Flyweight objects, ensuring that equivalent requests reuse the same instance.

Context| Stores the extrinsic state associated with an individual object and maintains a reference to its Flyweight.

Client| Uses the factory to obtain Flyweights and combines them with the appropriate contextual information.

The distinction between intrinsic and extrinsic state is the most important part of this pattern.

If we extract the wrong information, we risk sharing data that should belong to an individual object. That can lead to incorrect behaviour, particularly when the shared object is modified by one client and the changes affect others.

For that reason, Flyweight objects should generally be immutable.

Implementing Flyweight in C#

Let's implement the pattern using the ticket activity feed.

1\. Identifying intrinsic and extrinsic state

First, consider the information associated with an activity entry.

Some information belongs exclusively to an individual activity:

\- Activity ID.

\- Ticket reference.

\- Date and time.

\- Person who performed the action.

\- Event-specific details.

Other information depends only on the type of activity:

\- Display label.

\- Icon.

\- Colour.

\- Description template.

We can separate these into two groups.

Intrinsic state — shared| Extrinsic state — unique

Display label| Activity ID

Icon| Ticket reference

Colour| Date and time

Description template| Actor's display name

| Event-specific details

The intrinsic state is suitable for sharing because it remains the same for every activity of a particular type.

The extrinsic state must remain associated with the individual activity.

For example, two assignment events might use exactly the same icon, colour and display label. However, they could involve different tickets, different users and different dates.

Those differences must not be stored in the shared object.

2\. Defining the activity data

Let's begin by defining the possible activity types.

public enum TicketActivityKind

{

Created,

Assigned,

StatusChanged,

CommentAdded

}

Next, we define the information associated with an individual activity.

public sealed record TicketActivityEntry(

Guid ActivityId,

string TicketReference,

DateTimeOffset OccurredAt,

string ActorDisplayName,

TicketActivityKind Kind,

string? Details);

Each "TicketActivityEntry" represents a specific event.

For example, an assignment activity might contain the following information:

\- Activity ID: a unique identifier.

\- Ticket reference: "TCK-1042".

\- Date: the time the assignment occurred.

\- Actor: "Kabelo".

\- Kind: "Assigned".

\- Details: "Sarah".

Another assignment activity might contain a different ticket reference, actor and date.

These values are extrinsic state because they belong to the individual activity rather than the shared activity type.

3\. Creating the Flyweight

Now we create "TicketActivityFlyweight", which contains the information shared by activities of the same type.

public sealed record TicketActivityFlyweight(

string Label,

string Icon,

string Colour,

string DescriptionTemplate)

{

public string FormatDescription(

TicketActivityEntry activity)

{

return string.Format(

DescriptionTemplate,

activity.ActorDisplayName,

activity.Details ?? string.Empty);

}

}

The record contains four properties representing intrinsic state.

Notice that "FormatDescription()" receives a "TicketActivityEntry" as an argument.

The Flyweight does not store the actor's name, ticket reference or event-specific details. Instead, it receives the relevant information whenever a description needs to be generated.

This is an important part of the pattern: methods that require extrinsic state receive it through their parameters rather than storing it inside the shared object.

The use of a record also helps communicate the intended immutability of the Flyweight. Its properties are initialised when the object is created and cannot be reassigned through ordinary property setters.

The description templates follow a simple convention:

\- "{0}" represents the actor's display name.

\- "{1}" represents the event-specific details when the template needs a second value.

For example, ""{0} created this ticket."" uses only the actor, while ""{0} assigned this ticket to {1}."" uses both the actor and the assignee.

The implementation passes two arguments to "string.Format()". Extra arguments are permitted when a template uses only "{0}", so the creation and comment templates still work. However, keeping the placeholder convention clear makes the templates easier to maintain.

4\. Creating the Flyweight Factory

We now need a way to manage the shared objects.

If every client creates its own "TicketActivityFlyweight", we have not achieved anything. We would simply be creating the same objects repeatedly through a different class.

The Flyweight Factory solves this problem.

Its responsibility is to maintain a collection of existing Flyweights and return the appropriate instance when requested.

using System.Collections.Frozen;

public sealed class TicketActivityFlyweightFactory

{

private readonly FrozenDictionary&lt;

TicketActivityKind,

TicketActivityFlyweight> \_flyweights =

new Dictionary&lt;

TicketActivityKind,

TicketActivityFlyweight>

{

\[TicketActivityKind.Created\] = new(

"Ticket created",

"plus-circle",

"green",

"{0} created this ticket."),

\[TicketActivityKind.Assigned\] = new(

"Ticket assigned",

"user-check",

"blue",

"{0} assigned this ticket to {1}."),

\[TicketActivityKind.StatusChanged\] = new(

"Status changed",

"arrow-left-right",

"amber",

"{0} changed the status to {1}."),

\[TicketActivityKind.CommentAdded\] = new(

"Comment added",

"message-square",

"grey",

"{0} added a comment.")

}.ToFrozenDictionary();

public TicketActivityFlyweight GetFlyweight(

TicketActivityKind kind)

{

if (\_flyweights.TryGetValue(kind, out var flyweight))

{

return flyweight;

}

throw new ArgumentOutOfRangeException(

nameof(kind),

kind,

"Unsupported ticket activity kind.");

}

}

The factory creates one Flyweight for each supported activity type.

When a client requests a Flyweight, the factory retrieves the existing instance rather than creating another one.

For example:

var first = factory.GetFlyweight(

TicketActivityKind.Created);

var second = factory.GetFlyweight(

TicketActivityKind.Created);

Console.WriteLine(

ReferenceEquals(first, second)); // True

Both variables refer to the same object.

That is the key behaviour we want to achieve.

There is also an interesting .NET-specific detail in this implementation.

Instead of using an ordinary "Dictionary", we use "FrozenDictionary", available in modern .NET. It is an immutable dictionary optimised for situations where a collection is created infrequently but queried frequently.

This suits our example because the activity types are known in advance and the lookup collection does not need to change at runtime.

It is not a requirement of the Flyweight pattern, though. A normal dictionary is perfectly suitable when the collection is small, dynamic or frequently updated.

Microsoft Learn provides further information about ""FrozenDictionary&lt;TKey, TValue>"" (https://learn.microsoft.com/en-us/dotnet/api/system.collections.frozen.frozendictionary-2).

5\. Combining the Flyweight with individual activity data

We now have the shared objects, but we still need to associate each one with the correct activity.

This is where the Context participant comes in.

The context combines the individual activity information with a reference to the appropriate Flyweight.

public sealed record TicketActivityPresentation(

TicketActivityEntry Activity,

TicketActivityFlyweight Flyweight)

{

public string Description =>

Flyweight.FormatDescription(Activity);

}

"TicketActivityPresentation" holds two things:

\- The individual activity, which contains the extrinsic state.

\- The shared Flyweight, which contains the intrinsic state.

The "Description" property delegates formatting to the Flyweight, supplying the individual activity as context.

This allows the same Flyweight to generate different descriptions depending on the activity passed to it.

For example, consider two assignment activities:

var assignment1 = new TicketActivityEntry(

Guid.NewGuid(),

"TCK-1042",

DateTimeOffset.UtcNow,

"Kabelo",

TicketActivityKind.Assigned,

"Sarah");

var assignment2 = new TicketActivityEntry(

Guid.NewGuid(),

"TCK-1087",

DateTimeOffset.UtcNow,

"Michael",

TicketActivityKind.Assigned,

"John");

Both activities use the same assignment Flyweight.

However, their descriptions differ because the extrinsic information supplied to the Flyweight is different:

\- Kabelo assigned the first ticket to Sarah.

\- Michael assigned the second ticket to John.

The shared object contains the presentation rules, not the details of either assignment.

6\. Using the factory from the client

We can now create a component responsible for preparing activity entries for presentation.

public sealed class TicketActivityFeedRenderer(

TicketActivityFlyweightFactory flyweightFactory)

{

public IReadOnlyList&lt;TicketActivityPresentation> Render(

IEnumerable&lt;TicketActivityEntry> activities)

{

ArgumentNullException.ThrowIfNull(activities);

return activities

.Select(activity =>

new TicketActivityPresentation(

activity,

flyweightFactory.GetFlyweight(

activity.Kind)))

.ToArray();

}

}

The renderer receives activity entries and retrieves the appropriate Flyweight for each one.

It then creates a presentation context containing the activity and the shared Flyweight.

The client does not need to know how the Flyweight objects are created or stored. It simply requests the relevant instance from the factory.

The resulting presentation objects can be used by the application to display each activity's label, icon, colour and formatted description.

The important point is that the presentation contexts are individual objects, but their Flyweights are shared.

7\. Registering the factory with dependency injection

Since we are using ASP.NET Core, we can register the factory with the built-in dependency injection container.

builder.Services.AddSingleton&lt;

TicketActivityFlyweightFactory>();

builder.Services.AddTransient&lt;

TicketActivityFeedRenderer>();

The factory is registered as a singleton because it owns a collection of shared, immutable Flyweight objects.

All requests within the same application process can reuse the same factory and its cached instances.

The factory is suitable for singleton registration because:

\- Its lookup collection is immutable.

\- Its Flyweight objects are immutable.

\- It has no scoped dependencies.

\- Multiple requests can safely perform lookups concurrently.

This is consistent with Microsoft's guidance that singleton services must be thread-safe.

There is an important distinction here: registering the factory as a singleton does not mean that we are implementing the GoF Singleton pattern.

The Flyweight pattern allows multiple shared objects, each representing a different intrinsic state. The singleton registration simply ensures that the application reuses one factory instance within its dependency injection container.

In a horizontally scaled application, each application process will have its own factory and Flyweight instances. That is perfectly acceptable because these are shared in-memory presentation objects, not shared business data that must be synchronised between servers.

Microsoft Learn covers these considerations in its documentation on "dependency injection service lifetimes" (https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/service-lifetimes) and "dependency injection guidelines" (https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/guidelines).

When should you use the Flyweight pattern?

The Flyweight pattern is most useful when an application creates or manages large numbers of similar objects that contain repeated information.

Consider using it when:

\- You have many similar objects: Large collections contain repeated state that can be extracted and shared.

\- Memory consumption is a concern: Duplicate object allocations contribute meaningfully to the application's memory usage.

\- The shared information changes infrequently: Intrinsic state is stable and can safely be reused.

\- The extrinsic state can be separated: Unique information can remain with the individual object or be supplied when needed.

Examples outside our ticket-management application include:

\- Characters in a game sharing the same model, texture and animation data while maintaining individual positions and health.

\- Text editors sharing font and formatting information between thousands of characters.

\- Document-processing systems sharing metadata or formatting definitions across repeated elements.

However, the pattern should not be introduced simply because several objects contain similar properties.

If the number of objects is small, or the memory consumed by duplicated information is insignificant, the additional factory and context classes might not be worthwhile.

It is also important to measure the actual memory impact. Modern .NET applications already share some data through mechanisms such as string interning and static references. The Flyweight pattern is most useful when there are genuinely repeated object allocations that can be eliminated.

Advantages and trade-offs

Advantages

\- Reduces memory consumption: Shared objects avoid repeatedly allocating identical intrinsic state.

\- Encourages reuse: Multiple objects can use the same Flyweight rather than maintaining separate copies.

\- Separates shared and unique data: Intrinsic and extrinsic state have clearly defined responsibilities.

\- Supports large collections: Applications can manage many individual objects while maintaining a relatively small collection of shared Flyweights.

Trade-offs

\- Increases design complexity: Developers must identify and separate intrinsic and extrinsic state correctly.

\- Can introduce additional processing: Methods may need to receive extrinsic state as parameters instead of accessing it directly.

\- Requires careful handling of shared state: Mutable Flyweights can cause changes made by one client to affect other clients.

\- Can provide little benefit for small collections: The extra abstractions may cost more in complexity than the memory they save.

A further consideration is the lifecycle of the Flyweight cache.

In our example, the possible activity types are known in advance, so the factory can maintain a fixed collection.

In a system where Flyweights are created dynamically, the factory may need to add entries to its cache. This introduces additional considerations around memory growth, eviction and thread safety.

An unbounded cache can eventually become a memory problem of its own, particularly when the intrinsic state has a large number of possible combinations.

The Flyweight pattern is therefore not simply about sharing everything. It is about sharing the right information and managing the shared objects responsibly.

Flyweight vs other design patterns

Flyweight is sometimes confused with other patterns that involve object reuse or shared instances.

Pattern| Primary purpose| Key distinction

Flyweight| Shares common state between many objects.| Multiple clients reuse immutable objects while maintaining their own extrinsic state.

Singleton| Ensures a class has one shared instance within its intended scope.| A singleton represents one instance, whereas Flyweight can manage many instances with different intrinsic states.

Object Pool| Reuses expensive objects instead of repeatedly creating and destroying them.| A pooled object is generally checked out for use and returned, potentially with its state reset.

Factory Method| Delegates object creation to subclasses.| Factory Method focuses on which concrete object gets created, not on sharing existing instances to reduce memory usage.

The distinction between Flyweight and Object Pool is particularly important.

Both patterns can reduce object allocation, but they solve different problems.

Flyweight shares immutable intrinsic state between multiple clients at the same time.

Object Pool generally manages reusable objects that are temporarily made available to a client. A pooled object's state is usually retained internally and may be reset between uses.

Similarly, Flyweight and Singleton are not interchangeable. A Flyweight factory may manage several shared objects, while a Singleton ensures one instance of a particular class within its defined scope.

Conclusion

The Flyweight pattern addresses a memory-management problem that can become significant in applications handling large numbers of similar objects.

By separating intrinsic state from extrinsic state, we can share repeated information instead of allocating it independently for every instance.

Our ticket activity feed demonstrates this approach. Although the application may contain thousands of activity records, it only needs a small collection of shared presentation objects representing the supported activity types.

The individual activity records retain their unique information, while the shared Flyweights provide the common presentation rules.

However, Flyweight is a pattern that should be applied deliberately. Sharing objects introduces additional design considerations, and the memory savings depend on the amount of duplicated state that can actually be eliminated.

The key lesson: Sometimes the best way to manage a large number of objects is not to make each object smaller, but to recognise which information does not need to be stored repeatedly.

In the next article, we will explore the Proxy pattern, which introduces a substitute object that controls access to another object or resource.

Further reading

1\. Alexander Shvets — Dive Into Design Patterns

Structural Design Patterns, Flyweight chapter. Covers intrinsic and extrinsic state, the Flyweight Factory, applicability, implementation steps and the pattern's trade-offs.

2\. Vaskaran Sarcar — Design Patterns in C#, 2nd Edition

Chapter 10: Flyweight Pattern. Provides a C# implementation using a factory and shared vehicle objects, with additional discussion of memory usage, multithreading, advantages and the distinction between Flyweight and Object Pool.

3\. "FrozenDictionary&lt;TKey, TValue>" (https://learn.microsoft.com/en-us/dotnet/api/system.collections.frozen.frozendictionary-2)

Explains the immutable dictionary collection used in the example and when it is suitable for frequently queried, infrequently constructed lookup data.

4\. "Service Lifetimes" (https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/service-lifetimes)

Explains singleton, scoped and transient lifetimes, including the requirements for thread-safe singleton services.

5\. "Dependency Injection Guidelines" (https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/guidelines)

Provides guidance on designing services for dependency injection, thread safety and the implications of shared singleton instances.
