Context:

Objects of a type may be heavyweight but tend to have equal values and are read-only all or most of the time (e.g. character string).

Challenge:

To prevent resource duplication system wide, hiding the existence of the Flyweight Pool.

Skill:

Participants:

Flyweight:

The (hidden) sole source for Resources. A singleton. Responsible for creating resources, managing their lifespan and guaranteeing their uniqueness. Not exposed to the Client.

Resource Proxy:

A transparent resource wrapper used directly by the client (thus, effectively hiding the existence of the flyweight). A reference-counting proxy.

Resource Reference Counter:

A resource wrapper obtained by the Resource Proxy from the flyweight to control Resource lifespan. Responsible for alerting the flyweight to initiate its own disposal.

Resource:

stored inside the flyweight. Accessed through a Resource Proxy.

Signature:

Flyweight contains Smart Pointer Counters by key and creates Resources. Resource Proxies share Smart Pointer Counter, obtained from the Flyweight. Smart Pointer Counter contains Resource and notifies the flyweight.

Used patterns and idioms:

Singleton, Reference-counting proxy.

Used by:

Character string and similar widely used low-level types with significant duplication overhead.

Scope:

General (system programming).