Context:

Objects are heavyweight or encapsulate system-critical resources and are read only.

Challenge:

To prevent resource duplication, system wide.

Skill:

Participants:

Flyweight:

The sole supplier of Resources. A singleton. Responsible for creating Resources, managing their lifespan and guaranteeing their uniqueness.

Client:

Uses Resources obtained from the Flyweight.

Smart Resource Pointer:

A go-between, obtained from the flyweight to control Resource lifespan. A Reference-Counting Smart Pointer.

Smart Pointer Counter:

Stored in the Flyweight. Accessed through a Smart Resource Pointer. Responsible for alerting the Flyweight to initiate Resource (i.e. its own) disposal.

Resource:

Stored inside the Flyweight. Obtained exclusively through the Flyweight. Required to allow creation using unique key.

Signature:

Flyweight contains Smart Pointer Counters by key, creates Resources (which it keeps via the Smart Pointer Counters) as well as Smart Pointers (which it does not keep) that share a Smart Pointer Counter. Smart Pointer Counter contains a Resource and notifies the Flyweight. Client uses Smart Resource Pointers, obtained from the Flyweight.

Notes:

The "RC Smart pointer" may look at first like a viable alternative. However, it prevents duplication inside copy-conceived groups, rather than globally as required here.

Used patterns and idioms:

Reference-Counting Smart Pointer, Singleton.

Variations:

Invisible Flyweight Pool, Caching Flyweight Pool.

Used by:

Database replicators and similar infrastructure, typical of client/server architectures .

Source:

GOF (without the interface of Smart-Pointer and without reference counting).

Scope:

General.