Flyweight pattern

Uses your system voice; voice and rate in settings.

Snapshot

≈ 5 min read

Names in other languages

No names in other languages are held for this entry yet.

Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.

, often use the 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 concept was coined and first 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.

, often use the 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 concept was coined and first 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 (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. // 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 { Name = "ABC", Location = "XYZ", Website = "www.example.com" }; } public class MyObject { public string Name { get; set; } public string Company => Pointer.Company.Name; } 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 { private: const String name; public: explicit Tenant(StringView name): name{name} {} nodiscard String getName() const noexcept { return name; } }; // Registry acts as a factory and cache for Tenant flyweight objects class Registry { private: HashMap tenants; public: Registry() = default; nodiscard Tenant& findByName(StringView name) { if (!tenants.contains(name)) { tenants[name] = Tenant{name}; } return tenants[name]; } }; // Apartment maps a unique tenant to their room number. class Apartment { private: TreeMap occupants; Registry registry; public: Apartment() = default; void addOccupant(StringView name, int room) { occupants[room] = &registry.findByName(name); } void printTenants() { // room: int, tenant: Tenant for (const auto& [room, tenant] : occupants) { std::println("{} occupies room {}", tenant.name(), room); } } }; int main(int argc, char* argv[]) { Apartment apartment; apartment.addOccupant("David", 1); apartment.addOccupant("Sarah", 3); apartment.addOccupant("George", 2); apartment.addOccupant("Sarah", 12); apartment.addOccupant("Michael", 10); apartment.printTenants(); return 0; } 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);

See also

Copy-on-write Memoization Multiton

Text derived from https://en.wikipedia.org/w/index.php?oldid=1361148690 under CC BY-SA 4.0; modifications have been made.

Sources cited in this revision

4 named source(s) extracted from the cited revision. A source with no author is shown by its publication; nothing is invented.