Flyweight pattern
In computer programming, the flyweight software design pattern refers to an object that minimizes memory usage by sharing some of its data with other similar objects. The flyweight pattern is one of twenty-three GoF design patterns.
In other contexts, the idea of sharing data structures is called hash consing.
The term was first coined, and the idea extensively explored, by Paul Calder and Mark Linton in 1990 to efficiently handle glyph information in a WYSIWYG document editor. Similar techniques were already used in other systems, however, as early as 1988.
Overview
The flyweight pattern is useful when dealing with a large number of objects that share simple repeated elements which would use a large amount of memory if they were individually embedded. It is common to hold shared data in external data structures and pass it to the objects temporarily when they are used.A classic example are the data structures used representing characters in a word processor. Naively, each character in a document might have a glyph object containing its font outline, font metrics, and other formatting data. However, this would use hundreds or thousands of bytes of memory for each character. Instead, each character can have a reference to a glyph object shared by every instance of the same character in the document. This way, only the position of each character needs to be stored internally.
As a result, flyweight objects can:
- store intrinsic state that is invariant, context-independent and shareable
- provide an interface for passing in extrinsic state that is variant, context-dependent and can't be shared
Flyweight objects and pass in extrinsic state as necessary, reducing the number of physically created objects.Structure
The above UML class diagram shows:- the
Clientclass, which uses the flyweight pattern - the
FlyweightFactoryclass, which creates and sharesFlyweightobjects - the
Flyweightinterface, which takes in extrinsic state and performs an operation - the
Flyweight1class, which implementsFlyweightand stores intrinsic state
- The
Clientobject callsgetFlyweighton theFlyweightFactory, which returns aFlyweight1object. - After calling
operationon the returnedFlyweight1object, theClientagain callsgetFlyweighton theFlyweightFactory. - The
FlyweightFactoryreturns the already-existingFlyweight1object.Implementation details
Immutable objects are easily shared, but require creating new extrinsic objects whenever a change in state occurs. In contrast, mutable objects can share state. Mutability allows better object reuse via the caching and re-initialization of old, unused objects. Sharing is usually nonviable when state is highly variable.
Other primary concerns include retrieval, caching and concurrency.
Retrieval
The factory interface for creating or reusing flyweight objects is often a facade for a complex underlying system. For example, the factory interface is commonly implemented as a singleton to provide global access for creating flyweights.Generally speaking, the retrieval algorithm begins with a request for a new object via the factory interface.
The request is typically forwarded to an appropriate cache based on what kind of object it is. If the request is fulfilled by an object in the cache, it may be reinitialized and returned. Otherwise, a new object is instantiated. If the object is partitioned into multiple extrinsic sub-components, they will be pieced together before the object is returned.
Caching
There are two ways to cache flyweight objects: maintained and unmaintained caches.Objects with highly variable state can be cached with a FIFO structure. This structure maintains unused objects in the cache, with no need to search the cache.
In contrast, unmaintained caches have less upfront overhead: objects for the caches are initialized in bulk at compile time or startup. Once objects populate the cache, the object retrieval algorithm might have more overhead associated than the push/pop operations of a maintained cache.
When retrieving extrinsic objects with immutable state one must simply search the cache for an object with the state one desires. If no such object is found, one with that state must be initialized. When retrieving extrinsic objects with mutable state, the cache must be searched for an unused object to reinitialize if no used object is found. If there is no unused object available, a new object must be instantiated and added to the cache.
Separate caches can be used for each unique subclass of extrinsic object. Multiple caches can be optimized separately, associating a unique search algorithm with each cache. This object caching system can be encapsulated with the chain of responsibility pattern, which promotes loose coupling between components.
Concurrency
Special consideration must be taken into account where flyweight objects are created on multiple threads. If the list of values is finite and known in advance, the flyweights can be instantiated ahead of time and retrieved from a container on multiple threads with no contention. If flyweights are instantiated on multiple threads, there are two options:- Make flyweight instantiation single-threaded, thus introducing contention and ensuring one instance per value.
- Allow concurrent threads to create multiple flyweight instances, thus eliminating contention and allowing multiple instances per value.
Examples
C#
In this example, every instance of theMyObject class uses a Pointer class to provide data.// Defines Flyweight object that repeats itself.
public class Flyweight
public static class Pointer
public class MyObject
C++
The C++ Standard Template Library provides several containers that allow unique objects to be mapped to a key. The use of containers helps further reduce memory usage by removing the need for temporary objects to be created.import std;
template
using TreeMap = std::map
using String = std::string;
using StringView = std::string_view;
template
using HashMap = std::unordered_map
// Instances of Tenant will be the Flyweights
class Tenant ;
// Registry acts as a factory and cache for Tenant flyweight objects
class Registry ;
// Apartment maps a unique tenant to their room number.
class Apartment ;
int main
PHP
class Order
class CoffeeShop
$shop = new CoffeeShop;
$shop->takeOrder;
$shop->takeOrder;
$shop->takeOrder;
$shop->takeOrder;
$shop->takeOrder;
$shop->takeOrder;
$shop->takeOrder;
$shop->takeOrder;
$shop->takeOrder;
$shop->takeOrder;
$shop->takeOrder;
$shop->takeOrder;
$shop->service;
print;