In
computer programming
Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, the flyweight
software design pattern
In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine co ...
refers to an
object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ...
that minimizes
memory
Memory is the faculty of the mind by which data or information is encoded, stored, and retrieved when needed. It is the retention of information over time for the purpose of influencing future action. If past events could not be remembered ...
usage by sharing some of its data with other similar objects. The flyweight pattern is one of twenty-three well-known ''
GoF design patterns''.
These patterns promote flexible object-oriented software design, which is easier to implement, change, test, and reuse.
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 large numbers of objects with simple repeated elements that would use a large amount of memory if individually stored. 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
A word processor (WP) is a device or computer program that provides for input, editing, formatting, and output of text, often with some additional features.
Early word processors were stand-alone devices dedicated to the function, but current ...
. 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
Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a '' name'' ...
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 (for example, the code of character 'A' in a given character set)
* provide an interface for passing in ''extrinsic'' state that is variant, context-dependent and can't be shared (for example, the position of character 'A' in a text document)
Clients can reuse
Flyweight
objects and pass in extrinsic state as necessary, reducing the number of physically created objects.
Structure
The above
UML
The Unified Modeling Language (UML) is a general-purpose, developmental modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system.
The creation of UML was originally m ...
class diagram
In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, operations (or methods), and the rela ...
shows:
* the
Client
class, which uses the flyweight pattern
*the
FlyweightFactory
class, which
creates and shares Flyweight
objects
* the
Flyweight
interface
Interface or interfacing may refer to:
Academic journals
* ''Interface'' (journal), by the Electrochemical Society
* '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics''
* '' Int ...
, which takes in extrinsic state and performs an operation
*the
Flyweight1
class, which implements
Flyweight
and stores intrinsic state
The sequence diagram shows the following
run-time interactions:
# The
Client
object calls
getFlyweight(key)
on the
FlyweightFactory
, which returns a
Flyweight1
object.
# After calling
operation(extrinsicState)
on the returned
Flyweight1
object, the
Client
again calls
getFlyweight(key)
on the
FlyweightFactory
.
# The
FlyweightFactory
returns the already-existing
Flyweight1
object.
Implementation details
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 and
concurrency.
Retrieval
The
factory
A factory, manufacturing plant or a production plant is an industrial facility, often a complex consisting of several buildings filled with machinery, where workers manufacture items or operate machines which process each item into another. ...
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
Singleton may refer to:
Sciences, technology Mathematics
* Singleton (mathematics), a set with exactly one element
* Singleton field, used in conformal field theory Computing
* Singleton pattern, a design pattern that allows only one instance ...
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
Cache, caching, or caché may refer to:
Places United States
* Cache, Idaho, an unincorporated community
* Cache, Illinois, an unincorporated community
* Cache, Oklahoma, a city in Comanche County
* Cache, Utah, Cache County, Utah
* Cache County ...
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
Cache, caching, or caché may refer to:
Places United States
* Cache, Idaho, an unincorporated community
* Cache, Illinois, an unincorporated community
* Cache, Oklahoma, a city in Comanche County
* Cache, Utah, Cache County, Utah
* Cache County ...
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
The chain of responsibility is a policy concept used in Australian transport legislation to place legal obligations on parties in the transport supply chain or across transport industries generally. The concept was initially developed to apply ...
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.
To enable safe sharing between clients and threads, flyweight objects can be made into
immutable value objects, where two instances are considered equal if their values are equal.
This example from C# 9 uses records to create a value object representing flavours of coffee:
public record CoffeeFlavours(string flavour);
Example in C#
In this example every instance of the
MyObject
class uses a
Pointer
class to provide data.
// Defines Flyweight object that repeats itself.
public class Flyweight
public static class Pointer
public class MyObject
Example in Python
Attributes can be defined at the class-level instead of only for instances in
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
because classes are first-class objects in the language—meaning there are no restrictions on their use as they are the same as any other object. New-style class instances store instance data in a special attribute dictionary
instance.__dict__
. By default, accessed attributes are first looked up in this
__dict__
, and then fall back to the instance's class attributes next.
In this way, a class can effectively be a kind of Flyweight container for its instances.
Although Python classes are mutable by default, immutability can be emulated by overriding the class's
__setattr__
method so that it disallows changes to any Flyweight attributes.
# Instances of CheeseBrand will be the Flyweights
class CheeseBrand:
def __init__(self, brand: str, cost: float) -> None:
self.brand = brand
self.cost = cost
self._immutable = True # Disables future attributions
def __setattr__(self, name, value):
if getattr(self, "_immutable", False): # Allow initial attribution
raise RuntimeError("This object is immutable")
else:
super().__setattr__(name, value)
class CheeseShop:
menu = # Shared container to access the Flyweights
def __init__(self) -> None:
self.orders = # per-instance container with private attributes
def stock_cheese(self, brand: str, cost: float) -> None:
cheese = CheeseBrand(brand, cost)
self.menurand
The RAND Corporation (from the phrase "research and development") is an American nonprofit global policy think tank created in 1948 by Douglas Aircraft Company to offer research and analysis to the United States Armed Forces. It is finan ...
= cheese # Shared Flyweight
def sell_cheese(self, brand: str, units: int) -> None:
self.orders.setdefault(brand, 0)
self.ordersrand
The RAND Corporation (from the phrase "research and development") is an American nonprofit global policy think tank created in 1948 by Douglas Aircraft Company to offer research and analysis to the United States Armed Forces. It is finan ...
+= units # Instance attribute
def total_units_sold(self):
return sum(self.orders.values())
def total_income(self):
income = 0
for brand, units in self.orders.items():
income += self.menurand
The RAND Corporation (from the phrase "research and development") is an American nonprofit global policy think tank created in 1948 by Douglas Aircraft Company to offer research and analysis to the United States Armed Forces. It is finan ...
cost * units
return income
shop1 = CheeseShop()
shop2 = CheeseShop()
shop1.stock_cheese("white", 1.25)
shop1.stock_cheese("blue", 3.75)
# Now every CheeseShop have 'white' and 'blue' on the inventory
# The SAME 'white' and 'blue' CheeseBrand
shop1.sell_cheese("blue", 3) # Both can sell
shop2.sell_cheese("blue", 8) # But the units sold are stored per-instance
assert shop1.total_units_sold() 3
assert shop1.total_income() 3.75 * 3
assert shop2.total_units_sold() 8
assert shop2.total_income() 3.75 * 8
Example in C++
The C++
Standard Template Library
The Standard Template Library (STL) is a software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called ''algorithms'', '' ...
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.
#include
#include
Example in PHP
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);
See also
*
Copy-on-write
Copy-on-write (COW), sometimes referred to as implicit sharing or shadowing, is a resource-management technique used in computer programming to efficiently implement a "duplicate" or "copy" operation on modifiable resources. If a resource is dupl ...
*
Memoization
*
Multiton
References
{{DEFAULTSORT:Flyweight Pattern
Articles with example Java code
Software design patterns
Software optimization