
In
computer programming
Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, the flyweight
software design pattern
In software engineering, a software design pattern or design pattern is a general, reusable solution to a commonly occurring problem in many contexts in software design. A design pattern is not a rigid structure to be transplanted directly into s ...
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 a ...
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 remembe ...
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 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 structure
In computer science, a data structure is a data organization and storage format that is usually chosen for Efficiency, efficient Data access, access to data. More precisely, a data structure is a collection of data values, the relationships amo ...
s 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 word ...
. Naively, each character in a document might have a
glyph
A glyph ( ) is any kind of purposeful mark. In typography, a glyph is "the specific shape, design, or representation of a character". It is a particular graphical representation, in a particular typeface, of an element of written language. A ...
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
A 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 ''nam ...
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 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 re ...
shows:
* the
Client
class, which uses the flyweight pattern
*the
FlyweightFactory
class, which
creates and shares Flyweight
objects
* the
Flyweight
interface, 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
In object-oriented (OO) and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Secti ...
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 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. Th ...
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
Cache, caching, or caché may refer to:
Science and technology
* Cache (computing), a technique used in computer storage for easier data access
* Cache (biology) or hoarding, a food storing behavior of animals
* Cache (archaeology), artifacts p ...
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:
Science and technology
* Cache (computing), a technique used in computer storage for easier data access
* Cache (biology) or hoarding, a food storing behavior of animals
* Cache (archaeology), artifacts p ...
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.
To enable safe sharing between clients and threads, flyweight objects can be made into
immutable
In object-oriented (OO) and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Secti ...
value object
In computer science, a value object is a small object that represents a ''simple'' entity whose equality is not based on identity: i.e. two value objects are ''equal'' when they ''have'' the same ''value'', not necessarily being the ''same object' ...
s, where two instances are considered equal if their values are equal.
Examples
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
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
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), also called implicit sharing or shadowing, is a resource-management technique used in programming to manage shared data efficiently. Instead of copying data right away when multiple programs use it, the same data is shared ...
*
Memoization
In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls to pure functions and returning the cached result when the same inputs occur ag ...
*
Multiton
References
{{DEFAULTSORT:Flyweight Pattern
Articles with example Java code
Software design patterns
Software optimization