This article includes a list ofgeneral references, butit lacks sufficient correspondinginline citations. Please help toimprove this article byintroducing more precise citations.(May 2008) (Learn how and when to remove this message) |

Incomputer programming, theflyweightsoftware design pattern refers to anobject that minimizesmemory usage by sharing some of its data with other similar objects. The flyweight pattern is one of twenty-threeGoF design patterns.[1]
In other contexts, the idea of sharing data structures is calledhash consing.
The term was first coined, and the idea extensively explored, byPaul Calder andMark Linton in 1990[2] to efficiently handle glyph information in aWYSIWYG document editor.[3] Similar techniques were already used in other systems, however, as early as 1988.[4]
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 externaldata structures and pass it to the objects temporarily when they are used.
A classic example are the data structures used representing characters in aword processor. Naively, each character in a document might have aglyph 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 areference 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:[5]
Clients can reuseFlyweight objects and pass in extrinsic state as necessary, reducing the number of physically created objects.

The aboveUMLclass diagram shows:
Client class, which uses the flyweight patternFlyweightFactory class, whichcreates and sharesFlyweight objectsFlyweightinterface, which takes in extrinsic state and performs an operationFlyweight1 class, which implementsFlyweight and stores intrinsic stateThe sequence diagram shows the followingrun-time interactions:
Client object callsgetFlyweight(key) on theFlyweightFactory, which returns aFlyweight1 object.operation(extrinsicState) on the returnedFlyweight1 object, theClient again callsgetFlyweight(key) on theFlyweightFactory.FlyweightFactory returns the already-existingFlyweight1 object.There are multiple ways to implement the flyweight pattern. One example is mutability: whether the objects storing extrinsic flyweight state can change.
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 (how the end-client accesses the flyweight),caching andconcurrency.
Thefactory interface for creating or reusing flyweight objects is often afacade for a complex underlying system. For example, the factory interface is commonly implemented as asingleton 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 appropriatecache 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.
There are two ways tocache flyweight objects: maintained and unmaintained caches.
Objects with highly variable state can be cached with aFIFO 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 thechain of responsibility pattern, which promotes loose coupling between components.
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:
To enable safe sharing between clients and threads, flyweight objects can be made intoimmutablevalue objects, where two instances are considered equal if their values are equal.
In this example, every instance of theMyObject class uses aPointer class to provide data.
// Defines Flyweight object that repeats itself.publicclassFlyweight{publicstringName{get;set;}publicstringLocation{get;set;}publicstringWebsite{get;set;}publicbyte[]Logo{get;set;}}publicstaticclassPointer{publicstaticreadonlyFlyweightCompany=newFlyweight{Name="ABC",Location="XYZ",Website="www.example.com"};}publicclassMyObject{publicstringName{get;set;}publicstringCompany=>Pointer.Company.Name;}
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.
importstd;template<typenameK,typenameV>usingTreeMap=std::map<K,V>;usingString=std::string;usingStringView=std::string_view;template<typenameK,typenameV>usingHashMap=std::unordered_map<K,V>;// Instances of Tenant will be the FlyweightsclassTenant{private:constStringname;public:explicitTenant(StringViewname):name{name}{}[[nodiscard]]StringgetName()constnoexcept{returnname;}};// Registry acts as a factory and cache for Tenant flyweight objectsclassRegistry{private:HashMap<String,Tenant>tenants;public:Registry()=default;[[nodiscard]]Tenant&findByName(StringViewname){if(!tenants.contains(name)){tenants[name]=Tenant{name};}returntenants[name];}};// Apartment maps a unique tenant to their room number.classApartment{private:TreeMap<int,Tenant*>occupants;Registryregistry;public:Apartment()=default;voidaddOccupant(StringViewname,introom){occupants[room]=®istry.findByName(name);}voidprintTenants(){// room: int, tenant: Tenantfor(constauto&[room,tenant]:occupants){std::println("{} occupies room {}",tenant.name(),room);}}};intmain(intargc,char*argv[]){Apartmentapartment;apartment.addOccupant("David",1);apartment.addOccupant("Sarah",3);apartment.addOccupant("George",2);apartment.addOccupant("Sarah",12);apartment.addOccupant("Michael",10);apartment.printTenants();return0;}
<?phpclassCoffeeFlavour{privatestaticarray$CACHE=[];privatefunction__construct(privatestring$name){}publicstaticfunctionintern(string$name):self{self::$CACHE[$name]??=newself($name);returnself::$CACHE[$name];}publicstaticfunctionflavoursInCache():int{returncount(self::$CACHE);}publicfunction__toString():string{return$this->name;}}classOrder{privatefunction__construct(privateCoffeeFlavour$flavour,privateint$tableNumber){}publicstaticfunctioncreate(string$flavourName,int$tableNumber):self{$flavour=CoffeeFlavour::intern($flavourName);returnnewself($flavour,$tableNumber);}publicfunction__toString():string{return"Serving{$this->flavour} to table{$this->tableNumber}";}}classCoffeeShop{privatearray$orders=[];publicfunctiontakeOrder(string$flavour,int$tableNumber){$this->orders[]=Order::create($flavour,$tableNumber);}publicfunctionservice(){print(implode(PHP_EOL,$this->orders).PHP_EOL);}}$shop=newCoffeeShop();$shop->takeOrder("Cappuccino",2);$shop->takeOrder("Frappe",1);$shop->takeOrder("Espresso",1);$shop->takeOrder("Frappe",897);$shop->takeOrder("Cappuccino",97);$shop->takeOrder("Frappe",3);$shop->takeOrder("Espresso",3);$shop->takeOrder("Cappuccino",3);$shop->takeOrder("Espresso",96);$shop->takeOrder("Frappe",552);$shop->takeOrder("Cappuccino",121);$shop->takeOrder("Espresso",121);$shop->service();print("CoffeeFlavor objects in cache: ".CoffeeFlavour::flavoursInCache().PHP_EOL);
{{cite book}}: CS1 maint: multiple names: authors list (link)