Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Flyweight pattern
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Software design pattern for objects}} {{more footnotes|date=May 2008}} [[File:Linux-Mint-20-MATE-writer.png|alt=A screenshot of LibreOffice's Writer package.|thumb|Text editors, such as [[LibreOffice Writer]], often use the flyweight pattern.]] In [[computer programming]], the '''flyweight''' [[software design pattern]] refers to an [[Object (computer science)|object]] that minimizes [[Computer memory|memory]] usage by sharing some of its data with other similar objects. The flyweight pattern is one of twenty-three well-known ''[[Design Patterns|GoF design patterns]]''.<ref name="GoF">{{cite book|author=Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides|url=https://archive.org/details/designpatternsel00gamm/page/195|title=Design Patterns: Elements of Reusable Object-Oriented Software|publisher=Addison Wesley|year=1994|isbn=978-0-201-63361-0|pages=[https://archive.org/details/designpatternsel00gamm/page/195 195ff]}}</ref> 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<ref>{{cite book|last=Gamma|first=Erich|title=Design Patterns: Elements of Reusable Object-Oriented Software|title-link=Design Patterns (book)|author2=Richard Helm|author3=Ralph Johnson|author4=John Vlissides|publisher=[[Addison-Wesley]]|year=1995|isbn=978-0-201-63361-0|pages=[https://archive.org/details/designpatternsel00gamm/page/205 205β206]|author-link=Erich Gamma|author2-link=Richard Helm|author3-link=Ralph Johnson (computer scientist)|author4-link=John Vlissides}} </ref> to efficiently handle glyph information in a [[WYSIWYG|WYSIWYG document editor]].<ref> {{cite conference|last1=Calder|first1=Paul R.|last2=Linton|first2=Mark A.|title=Proceedings of the 3rd annual ACM SIGGRAPH symposium on User interface software and technology - UIST '90 |date=October 1990|chapter=Glyphs: Flyweight Objects for User Interfaces|conference=The 3rd Annual [[ACM SIGGRAPH]] Symposium on User Interface Software and Technology|location=Snowbird, Utah, United States|pages=92β101|doi=10.1145/97924.97935|isbn=0-89791-410-4}} </ref> Similar techniques were already used in other systems, however, as early as 1988.<ref> {{cite conference|last1=Weinand|first1=Andre|last2=Gamma|first2=Erich|last3=Marty|first3=Rudolf|year=1988|title=ET++βan object oriented application framework in C++|conference=[[OOPSLA]] (Object-Oriented Programming Systems, Languages and Applications)|location=San Diego, California, United States|pages=46β57|citeseerx=10.1.1.471.8796|doi=10.1145/62083.62089|isbn=0-89791-284-5}} </ref> ==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]]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]]. 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 (computer science)|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:<ref>{{Cite web|date=2019-01-28|title=Implementing Flyweight Patterns in Java|url=https://www.developer.com/design/implementing-flyweight-patterns-in-java/|access-date=2021-06-12|website=Developer.com|language=en-US}}</ref> * 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 <code>Flyweight</code> objects and pass in extrinsic state as necessary, reducing the number of physically created objects. === Structure === [[File:w3sDesign Flyweight Design Pattern UML.jpg|frame|none|A sample UML class and [[sequence diagram]] for the Flyweight design pattern.<ref>{{cite web|title=The Flyweight design pattern - Structure and Collaboration|url=http://w3sdesign.com/?gr=s06&ugr=struct|website=w3sDesign.com|access-date=2017-08-12}}</ref>]] The above [[UML]] [[class diagram]] shows: * the <code>Client</code> class, which uses the flyweight pattern *the <code>FlyweightFactory</code> class, which [[Factory class|creates and shares <code>Flyweight</code> objects]] * the <code>Flyweight</code> [[Interface (computing)|interface]], which takes in extrinsic state and performs an operation *the <code>Flyweight1</code> class, which implements <code>Flyweight</code> and stores intrinsic state The sequence diagram shows the following [[Runtime (program lifecycle phase)|run-time]] interactions: # The <code>Client</code> object calls <code>getFlyweight(key)</code> on the <code>FlyweightFactory</code>, which returns a <code>Flyweight1</code> object. # After calling <code>operation(extrinsicState)</code> on the returned <code>Flyweight1</code> object, the <code>Client</code> again calls <code>getFlyweight(key)</code> on the <code>FlyweightFactory</code>. # The <code>FlyweightFactory</code> returns the already-existing <code>Flyweight1</code> 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 (computer science)|concurrency]]. === Retrieval === The [[Factory (object-oriented programming)|factory]] interface for creating or reusing flyweight objects is often a [[Facade pattern|facade]] for a complex underlying system. For example, the factory interface is commonly implemented as a [[Singleton pattern|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 (computing)|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 (computing)|cache]] flyweight objects: maintained and unmaintained caches. Objects with highly variable state can be cached with a [[FIFO (computing and electronics)|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|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]] [[value object]]s, where two instances are considered equal if their values are equal. == Examples == === C# === In this example, every instance of the <code>MyObject</code> class uses a <code>Pointer</code> class to provide data. <syntaxhighlight lang="csharp"> // Defines Flyweight object that repeats itself. public class Flyweight { public string Name { get; set; } public string Location { get; set; } public string Website { get; set; } public byte[] Logo { get; set; } } public static class Pointer { public static readonly Flyweight Company = new Flyweight {"ABC","XYZ","www.example.com"}; } public class MyObject { public string Name { get; set; } public string Company => Pointer.Company.Name; } </syntaxhighlight> === 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. <syntaxhighlight lang="c++">#include <iostream> #include <map> #include <string> // Instances of Tenant will be the Flyweights class Tenant { public: Tenant(const std::string& name = "") : m_name(name) {} std::string name() const { return m_name; } private: std::string m_name; }; // Registry acts as a factory and cache for Tenant flyweight objects class Registry { public: Registry() : tenants() {} Tenant& findByName(const std::string& name) { if (!tenants.contains(name)) { tenants[name] = Tenant{name}; } return tenants[name]; } private: std::map<std::string, Tenant> tenants; }; // Apartment maps a unique tenant to their room number. class Apartment { public: Apartment() : m_occupants(), m_registry() {} void addOccupant(const std::string& name, int room) { m_occupants[room] = &m_registry.findByName(name); } void tenants() { for (const auto &i : m_occupants) { const int& room = i.first; const auto& tenant = i.second; std::cout << tenant->name() << " occupies room " << room << std::endl; } } private: std::map<int, Tenant*> m_occupants; Registry m_registry; }; int main() { Apartment apartment; apartment.addOccupant("David", 1); apartment.addOccupant("Sarah", 3); apartment.addOccupant("George", 2); apartment.addOccupant("Sarah", 12); apartment.addOccupant("Michael", 10); apartment.tenants(); return 0; } </syntaxhighlight> === PHP === <syntaxhighlight lang="php"><?php class CoffeeFlavour { private static array $CACHE = []; private function __construct(private string $name) {} public static function intern(string $name): self { self::$CACHE[$name] ??= new self($name); return self::$CACHE[$name]; } public static function flavoursInCache(): int { return count(self::$CACHE); } public function __toString(): string { return $this->name; } } class Order { private function __construct( private CoffeeFlavour $flavour, private int $tableNumber ) {} public static function create(string $flavourName, int $tableNumber): self { $flavour = CoffeeFlavour::intern($flavourName); return new self($flavour, $tableNumber); } public function __toString(): string { return "Serving {$this->flavour} to table {$this->tableNumber}"; } } class CoffeeShop { private array $orders = []; public function takeOrder(string $flavour, int $tableNumber) { $this->orders[] = Order::create($flavour, $tableNumber); } public function service() { print(implode(PHP_EOL, $this->orders).PHP_EOL); } } $shop = new CoffeeShop(); $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); </syntaxhighlight> ==See also== * [[Copy-on-write]] * [[Memoization]] * [[Multiton]] == References == {{reflist}} {{Design Patterns Patterns}} {{DEFAULTSORT:Flyweight Pattern}} [[Category:Articles with example Java code]] [[Category:Software design patterns]] [[Category:Software optimization]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite book
(
edit
)
Template:Cite conference
(
edit
)
Template:Cite web
(
edit
)
Template:Design Patterns Patterns
(
edit
)
Template:More footnotes
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)