<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>http://debianws.lexgopc.com/wiki143/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=2605%3A8D80%3A6A21%3A9026%3A886A%3ABD7C%3AFA60%3A99CB</id>
	<title>wiki143 - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="http://debianws.lexgopc.com/wiki143/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=2605%3A8D80%3A6A21%3A9026%3A886A%3ABD7C%3AFA60%3A99CB"/>
	<link rel="alternate" type="text/html" href="http://debianws.lexgopc.com/wiki143/index.php?title=Special:Contributions/2605:8D80:6A21:9026:886A:BD7C:FA60:99CB"/>
	<updated>2026-06-01T07:11:13Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.43.1</generator>
	<entry>
		<id>http://debianws.lexgopc.com/wiki143/index.php?title=Flyweight_pattern&amp;diff=3395377</id>
		<title>Flyweight pattern</title>
		<link rel="alternate" type="text/html" href="http://debianws.lexgopc.com/wiki143/index.php?title=Flyweight_pattern&amp;diff=3395377"/>
		<updated>2025-10-18T02:14:57Z</updated>

		<summary type="html">&lt;p&gt;2605:8D80:6A21:9026:886A:BD7C:FA60:99CB: /* C++ */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{Short description|Software design pattern for objects}}&lt;br /&gt;
{{more footnotes|date=May 2008}}&lt;br /&gt;
[[File:Linux-Mint-20-MATE-writer.png|alt=A screenshot of LibreOffice&#039;s Writer package.|thumb|Text editors, such as [[LibreOffice Writer]], often use the flyweight pattern.]]&lt;br /&gt;
In [[computer programming]], the &#039;&#039;&#039;flyweight&#039;&#039;&#039; [[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 &#039;&#039;[[Design Patterns|GoF design patterns]]&#039;&#039;.&amp;lt;ref name=&amp;quot;GoF&amp;quot;&amp;gt;{{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]}}&amp;lt;/ref&amp;gt; These patterns promote flexible object-oriented software design, which is easier to implement, change, test, and reuse.&lt;br /&gt;
&lt;br /&gt;
In other contexts, the idea of sharing data structures is called [[hash consing]].&lt;br /&gt;
&lt;br /&gt;
The term was first coined, and the idea extensively explored, by [[Paul Calder]] and [[Mark Linton]] in 1990&amp;lt;ref&amp;gt;{{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}}&lt;br /&gt;
&amp;lt;/ref&amp;gt; to efficiently handle glyph information in a [[WYSIWYG|WYSIWYG document editor]].&amp;lt;ref&amp;gt;&lt;br /&gt;
{{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 &#039;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}}&lt;br /&gt;
&amp;lt;/ref&amp;gt; Similar techniques were already used in other systems, however, as early as 1988.&amp;lt;ref&amp;gt;&lt;br /&gt;
{{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}}&lt;br /&gt;
&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Overview== &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
As a result, flyweight objects can:&amp;lt;ref&amp;gt;{{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}}&amp;lt;/ref&amp;gt; &lt;br /&gt;
* store &#039;&#039;intrinsic&#039;&#039; state that is invariant, context-independent and shareable (for example, the code of character &#039;A&#039; in a given character set)&lt;br /&gt;
* provide an interface for passing in &#039;&#039;extrinsic&#039;&#039; state that is variant, context-dependent and can&#039;t be shared (for example, the position of character &#039;A&#039; in a text document)&lt;br /&gt;
&lt;br /&gt;
Clients can reuse &amp;lt;code&amp;gt;Flyweight&amp;lt;/code&amp;gt; objects and pass in extrinsic state as necessary, reducing the number of physically created objects.&lt;br /&gt;
&lt;br /&gt;
=== Structure ===&lt;br /&gt;
[[File:w3sDesign Flyweight Design Pattern UML.jpg|frame|none|A sample UML class and [[sequence diagram]] for the Flyweight design pattern.&amp;lt;ref&amp;gt;{{cite web|title=The Flyweight design pattern - Structure and Collaboration|url=http://w3sdesign.com/?gr=s06&amp;amp;ugr=struct|website=w3sDesign.com|access-date=2017-08-12}}&amp;lt;/ref&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
The above [[UML]] [[class diagram]] shows:&lt;br /&gt;
&lt;br /&gt;
* the &amp;lt;code&amp;gt;Client&amp;lt;/code&amp;gt; class, which uses the flyweight pattern&lt;br /&gt;
*the &amp;lt;code&amp;gt;FlyweightFactory&amp;lt;/code&amp;gt; class, which [[Factory class|creates and shares &amp;lt;code&amp;gt;Flyweight&amp;lt;/code&amp;gt; objects]]&lt;br /&gt;
* the &amp;lt;code&amp;gt;Flyweight&amp;lt;/code&amp;gt; [[Interface (computing)|interface]], which takes in extrinsic state and performs an operation &lt;br /&gt;
*the &amp;lt;code&amp;gt;Flyweight1&amp;lt;/code&amp;gt; class, which implements &amp;lt;code&amp;gt;Flyweight&amp;lt;/code&amp;gt; and stores intrinsic state&lt;br /&gt;
&lt;br /&gt;
The sequence diagram shows the following [[Runtime (program lifecycle phase)|run-time]] interactions:&lt;br /&gt;
&lt;br /&gt;
# The &amp;lt;code&amp;gt;Client&amp;lt;/code&amp;gt; object calls &amp;lt;code&amp;gt;getFlyweight(key)&amp;lt;/code&amp;gt; on the &amp;lt;code&amp;gt;FlyweightFactory&amp;lt;/code&amp;gt;, which returns a &amp;lt;code&amp;gt;Flyweight1&amp;lt;/code&amp;gt; object.&lt;br /&gt;
# After calling &amp;lt;code&amp;gt;operation(extrinsicState)&amp;lt;/code&amp;gt; on the returned &amp;lt;code&amp;gt;Flyweight1&amp;lt;/code&amp;gt; object, the &amp;lt;code&amp;gt;Client&amp;lt;/code&amp;gt; again calls &amp;lt;code&amp;gt;getFlyweight(key)&amp;lt;/code&amp;gt; on the &amp;lt;code&amp;gt;FlyweightFactory&amp;lt;/code&amp;gt;.&lt;br /&gt;
# The &amp;lt;code&amp;gt;FlyweightFactory&amp;lt;/code&amp;gt; returns the already-existing &amp;lt;code&amp;gt;Flyweight1&amp;lt;/code&amp;gt; object.&lt;br /&gt;
&lt;br /&gt;
== Implementation details ==&lt;br /&gt;
There are multiple ways to implement the flyweight pattern. One example is mutability: whether the objects storing extrinsic flyweight state can change.&lt;br /&gt;
&lt;br /&gt;
[[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.&lt;br /&gt;
&lt;br /&gt;
Other primary concerns include retrieval (how the end-client accesses the flyweight), [[caching]] and [[Concurrency (computer science)|concurrency]].&lt;br /&gt;
&lt;br /&gt;
=== Retrieval === &lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
Generally speaking, the retrieval algorithm begins with a request for a new object via the factory interface.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== Caching ===&lt;br /&gt;
There are two ways to [[Cache (computing)|cache]] flyweight objects: maintained and unmaintained caches.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
=== Concurrency ===&lt;br /&gt;
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:&lt;br /&gt;
&lt;br /&gt;
# Make flyweight instantiation single-threaded, thus introducing contention and ensuring one instance per value.&lt;br /&gt;
# Allow concurrent threads to create multiple flyweight instances, thus eliminating contention and allowing multiple instances per value.&lt;br /&gt;
&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
== Examples ==&lt;br /&gt;
&lt;br /&gt;
=== C# ===&lt;br /&gt;
In this example, every instance of the &amp;lt;code&amp;gt;MyObject&amp;lt;/code&amp;gt; class uses a &amp;lt;code&amp;gt;Pointer&amp;lt;/code&amp;gt; class to provide data.&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;csharp&amp;quot;&amp;gt;&lt;br /&gt;
// Defines Flyweight object that repeats itself.&lt;br /&gt;
public class Flyweight&lt;br /&gt;
{&lt;br /&gt;
    public string Name { get; set; }&lt;br /&gt;
    public string Location { get; set; }&lt;br /&gt;
    public string Website { get; set; }&lt;br /&gt;
    public byte[] Logo { get; set; }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public static class Pointer&lt;br /&gt;
{&lt;br /&gt;
    public static readonly Flyweight Company = new Flyweight { Name = &amp;quot;ABC&amp;quot;, Location = &amp;quot;XYZ&amp;quot;, Website = &amp;quot;www.example.com&amp;quot; };&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
public class MyObject&lt;br /&gt;
{&lt;br /&gt;
    public string Name { get; set; }&lt;br /&gt;
    public string Company =&amp;gt; Pointer.Company.Name;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== C++ ===&lt;br /&gt;
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.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;c++&amp;quot;&amp;gt;&lt;br /&gt;
import std;&lt;br /&gt;
&lt;br /&gt;
template &amp;lt;typename K, typename V&amp;gt;&lt;br /&gt;
using TreeMap = std::map&amp;lt;K, V&amp;gt;;&lt;br /&gt;
using String = std::string;&lt;br /&gt;
using StringView = std::string_view;&lt;br /&gt;
template &amp;lt;typename K, typename V&amp;gt;&lt;br /&gt;
using HashMap = std::unordered_map&amp;lt;K, V&amp;gt;;&lt;br /&gt;
&lt;br /&gt;
// Instances of Tenant will be the Flyweights&lt;br /&gt;
class Tenant {&lt;br /&gt;
private:&lt;br /&gt;
    const String name;&lt;br /&gt;
public:&lt;br /&gt;
    explicit Tenant(StringView name): &lt;br /&gt;
        name{name} {}&lt;br /&gt;
&lt;br /&gt;
    [[nodiscard]]&lt;br /&gt;
    String getName() const noexcept {&lt;br /&gt;
        return name;&lt;br /&gt;
    }&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
// Registry acts as a factory and cache for Tenant flyweight objects&lt;br /&gt;
class Registry {&lt;br /&gt;
private:&lt;br /&gt;
    HashMap&amp;lt;String, Tenant&amp;gt; tenants;&lt;br /&gt;
public:&lt;br /&gt;
    Registry() = default;&lt;br /&gt;
&lt;br /&gt;
    [[nodiscard]]&lt;br /&gt;
    Tenant&amp;amp; findByName(StringView name) {&lt;br /&gt;
        if (!tenants.contains(name)) {&lt;br /&gt;
            tenants[name] = Tenant{name};&lt;br /&gt;
        }&lt;br /&gt;
        return tenants[name];&lt;br /&gt;
    }&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
// Apartment maps a unique tenant to their room number.&lt;br /&gt;
class Apartment {&lt;br /&gt;
private:&lt;br /&gt;
    TreeMap&amp;lt;int, Tenant*&amp;gt; occupants;&lt;br /&gt;
    Registry registry;&lt;br /&gt;
public:&lt;br /&gt;
    Apartment() = default;&lt;br /&gt;
&lt;br /&gt;
    void addOccupant(StringView name, int room) {&lt;br /&gt;
        occupants[room] = &amp;amp;registry.findByName(name);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    void printTenants() {&lt;br /&gt;
        // room: int, tenant: Tenant&lt;br /&gt;
        for (const auto&amp;amp; [room, tenant] : occupants) {&lt;br /&gt;
            std::println(&amp;quot;{} occupies room {}&amp;quot;, tenant.name(), room);&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
};&lt;br /&gt;
&lt;br /&gt;
int main(int argc, char* argv[]) {&lt;br /&gt;
    Apartment apartment;&lt;br /&gt;
    apartment.addOccupant(&amp;quot;David&amp;quot;, 1);&lt;br /&gt;
    apartment.addOccupant(&amp;quot;Sarah&amp;quot;, 3);&lt;br /&gt;
    apartment.addOccupant(&amp;quot;George&amp;quot;, 2);&lt;br /&gt;
    apartment.addOccupant(&amp;quot;Sarah&amp;quot;, 12);&lt;br /&gt;
    apartment.addOccupant(&amp;quot;Michael&amp;quot;, 10);&lt;br /&gt;
    apartment.printTenants();&lt;br /&gt;
&lt;br /&gt;
    return 0;&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=== PHP ===&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;php&amp;quot;&amp;gt;&amp;lt;?php&lt;br /&gt;
&lt;br /&gt;
class CoffeeFlavour {&lt;br /&gt;
&lt;br /&gt;
    private static array $CACHE = [];&lt;br /&gt;
&lt;br /&gt;
    private function __construct(private string $name) {}&lt;br /&gt;
&lt;br /&gt;
    public static function intern(string $name): self {&lt;br /&gt;
        self::$CACHE[$name] ??= new self($name);&lt;br /&gt;
        return self::$CACHE[$name];&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public static function flavoursInCache(): int {&lt;br /&gt;
        return count(self::$CACHE);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public function __toString(): string {&lt;br /&gt;
        return $this-&amp;gt;name;&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class Order {&lt;br /&gt;
&lt;br /&gt;
    private function __construct(&lt;br /&gt;
        private CoffeeFlavour $flavour,&lt;br /&gt;
        private int $tableNumber&lt;br /&gt;
    ) {}&lt;br /&gt;
&lt;br /&gt;
    public static function create(string $flavourName, int $tableNumber): self {&lt;br /&gt;
        $flavour = CoffeeFlavour::intern($flavourName);&lt;br /&gt;
        return new self($flavour, $tableNumber);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public function __toString(): string {&lt;br /&gt;
        return &amp;quot;Serving {$this-&amp;gt;flavour} to table {$this-&amp;gt;tableNumber}&amp;quot;;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class CoffeeShop {&lt;br /&gt;
&lt;br /&gt;
    private array $orders = [];&lt;br /&gt;
&lt;br /&gt;
    public function takeOrder(string $flavour, int $tableNumber) {&lt;br /&gt;
        $this-&amp;gt;orders[] = Order::create($flavour, $tableNumber);&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
    public function service() {&lt;br /&gt;
        print(implode(PHP_EOL, $this-&amp;gt;orders).PHP_EOL);&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
$shop = new CoffeeShop();&lt;br /&gt;
$shop-&amp;gt;takeOrder(&amp;quot;Cappuccino&amp;quot;, 2);&lt;br /&gt;
$shop-&amp;gt;takeOrder(&amp;quot;Frappe&amp;quot;, 1);&lt;br /&gt;
$shop-&amp;gt;takeOrder(&amp;quot;Espresso&amp;quot;, 1);&lt;br /&gt;
$shop-&amp;gt;takeOrder(&amp;quot;Frappe&amp;quot;, 897);&lt;br /&gt;
$shop-&amp;gt;takeOrder(&amp;quot;Cappuccino&amp;quot;, 97);&lt;br /&gt;
$shop-&amp;gt;takeOrder(&amp;quot;Frappe&amp;quot;, 3);&lt;br /&gt;
$shop-&amp;gt;takeOrder(&amp;quot;Espresso&amp;quot;, 3);&lt;br /&gt;
$shop-&amp;gt;takeOrder(&amp;quot;Cappuccino&amp;quot;, 3);&lt;br /&gt;
$shop-&amp;gt;takeOrder(&amp;quot;Espresso&amp;quot;, 96);&lt;br /&gt;
$shop-&amp;gt;takeOrder(&amp;quot;Frappe&amp;quot;, 552);&lt;br /&gt;
$shop-&amp;gt;takeOrder(&amp;quot;Cappuccino&amp;quot;, 121);&lt;br /&gt;
$shop-&amp;gt;takeOrder(&amp;quot;Espresso&amp;quot;, 121);&lt;br /&gt;
$shop-&amp;gt;service();&lt;br /&gt;
print(&amp;quot;CoffeeFlavor objects in cache: &amp;quot;.CoffeeFlavour::flavoursInCache().PHP_EOL);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==See also==&lt;br /&gt;
* [[Copy-on-write]]&lt;br /&gt;
* [[Memoization]]&lt;br /&gt;
* [[Multiton]]&lt;br /&gt;
&lt;br /&gt;
== References ==&lt;br /&gt;
{{reflist}}&lt;br /&gt;
&lt;br /&gt;
{{Design Patterns Patterns}}&lt;br /&gt;
&lt;br /&gt;
{{DEFAULTSORT:Flyweight Pattern}}&lt;br /&gt;
[[Category:Articles with example Java code]]&lt;br /&gt;
[[Category:Software design patterns]]&lt;br /&gt;
[[Category:Software optimization]]&lt;/div&gt;</summary>
		<author><name>2605:8D80:6A21:9026:886A:BD7C:FA60:99CB</name></author>
	</entry>
	<entry>
		<id>http://debianws.lexgopc.com/wiki143/index.php?title=Object%E2%80%93relational_mapping&amp;diff=3199429</id>
		<title>Object–relational mapping</title>
		<link rel="alternate" type="text/html" href="http://debianws.lexgopc.com/wiki143/index.php?title=Object%E2%80%93relational_mapping&amp;diff=3199429"/>
		<updated>2025-10-17T20:22:39Z</updated>

		<summary type="html">&lt;p&gt;2605:8D80:6A21:9026:886A:BD7C:FA60:99CB: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;{{short description|Programming technique}}&lt;br /&gt;
{{Distinguish|Object–role modeling}}&lt;br /&gt;
{{Use dmy dates|date=June 2019}}&lt;br /&gt;
{{More citations needed|date=May 2009}}&lt;br /&gt;
&#039;&#039;&#039;Object–relational mapping&#039;&#039;&#039; (&#039;&#039;&#039;ORM&#039;&#039;&#039;, &#039;&#039;&#039;O/RM&#039;&#039;&#039;, and &#039;&#039;&#039;O/R mapping tool&#039;&#039;&#039;) in [[computer science]] is a [[Computer programming|programming]] technique for converting data between a [[relational database]] and the memory (usually the [[Memory management#HEAP|heap]]) of an [[Object-oriented programming|object-oriented]] programming language. This creates, in effect, a virtual [[object database]] that can be used from within the program.&lt;br /&gt;
&lt;br /&gt;
In [[object-oriented programming]], [[data management|data-management]] tasks act on [[object (computer science)|object]]s that combine [[scalar (computing)|scalar]] values into objects. For example, consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a &amp;quot;Person [[Object (computer science)|object]]&amp;quot; with an [[attribute (computing)|attribute/field]] to hold each data item that the entry comprises: the person&#039;s name, a list of phone numbers, and a list of addresses. The list of phone numbers would itself contain &amp;quot;PhoneNumber objects&amp;quot; and so on. Each such address-book entry is treated as a single object by the programming language (it can be referenced by a single variable containing a pointer to the object, for instance). Various [[Method (computer programming)|methods]] can be associated with the object, such as methods to return the preferred phone number, the home address, and so on.&lt;br /&gt;
&lt;br /&gt;
By contrast, relational databases, such as [[SQL]], group scalars into [[tuples]], which are then enumerated in [[Table (database)|tables]]. Tuples and objects have some general similarity, in that they are both ways to collect values into named fields such that the whole collection can be manipulated as a single compound entity. They have many differences, though, in particular: lifecycle management (row insertion and deletion, versus [[Garbage collection (computer science)|garbage collection]] or [[reference counting]]), references to other entities (object references, versus foreign key references), and inheritance (non-existent in relational databases). As well, objects are managed on-heap and are under full control of a single process, while database tuples are shared and must incorporate locking, merging, and retry. Object–relational mapping provides automated support for mapping tuples to objects and back, while accounting for all of these differences.&amp;lt;ref name=&amp;quot;hibernate-orm-overview&amp;quot;&amp;gt;&lt;br /&gt;
{{cite web |title=What is Object/Relational Mapping? |url=http://www.hibernate.org/about/orm |access-date=27 January 2022 |work=Hibernate Overview |publisher=JBOSS Hibernate |language=en-US}}&lt;br /&gt;
&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The heart of the problem involves translating the logical representation of the objects into an atomized form that is capable of being stored in the database while preserving the properties of the objects and their relationships so that they can be reloaded as objects when needed. If this storage and retrieval functionality is implemented, the objects are said to be [[persistence (computer science)|persistent]].&amp;lt;ref name=hibernate-orm-overview /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Overview==&lt;br /&gt;
Implementation-specific details of storage drivers are generally wrapped in an API in the programming language in use, exposing methods to interact with the storage medium in a way which is simpler and more in line with the paradigms of surrounding code.&lt;br /&gt;
&lt;br /&gt;
The following is a simple example, written in [[C Sharp (programming language)|C#]] code, to execute a query written in [[SQL]] using a database engine.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;csharp&amp;quot;&amp;gt;&lt;br /&gt;
using System.Collections.Generic;&lt;br /&gt;
&lt;br /&gt;
string sql = &amp;quot;SELECT id, first_name, last_name, phone, birth_date, sex, age FROM persons WHERE id = 10&amp;quot;;&lt;br /&gt;
List&amp;lt;Person&amp;gt; result = context.Persons.FromSqlRaw(sql).ToList();&lt;br /&gt;
string name = result[0][&amp;quot;first_name&amp;quot;];&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In contrast, the following makes use of an ORM-job API which makes it possible to write code that naturally makes use of the features of the language.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;csharp&amp;quot;&amp;gt;&lt;br /&gt;
Person person = repository.GetPerson(10);&lt;br /&gt;
string firstName = person.GetFirstName();&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The case above makes use of an object representing the storage repository and methods of that object. Other frameworks might provide code as static methods, as in the example below, and yet other methods may not implement an object-oriented system at all. Often the choice of paradigm is made for the best fit of the ORM into the surrounding language&#039;s design principles.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;syntaxhighlight lang=&amp;quot;csharp&amp;quot;&amp;gt;&lt;br /&gt;
Person person = Person.Get(10);&lt;br /&gt;
&amp;lt;/syntaxhighlight&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==Comparison with traditional data access techniques==&lt;br /&gt;
Compared to traditional techniques of exchange between an object-oriented language and a relational database, ORM often reduces the amount of code that needs to be written.&amp;lt;ref&amp;gt;{{cite journal | date= 1998 | doi=10.1109/2.730734 | issue=11 | journal=Computer | pages=33–40 | publisher=Institute of Electrical and Electronics Engineers (IEEE) | title=Solving the Java object storage problem |quote=For this exercise, 496 lines of code were needed using the ODMG Java Binding compared to 1,923 lines of code using JDBC. | url=https://www.service-architecture.com/articles/object-relational-mapping/transparent-persistence-vs-jdbc-call-level-interface.html | vauthors=((Barry, D.)), ((Stanienda, T.)) | volume=31 }}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Disadvantages of ORM tools generally stem from the high level of [[Database abstraction layer|abstraction]] obscuring what is actually happening in the implementation code.&lt;br /&gt;
&lt;br /&gt;
==Object-oriented databases==&lt;br /&gt;
Another approach is to use an [[object database|object-oriented database management system]] (OODBMS) or [[document-oriented database]]s such as native [[XML database]]s that provide more flexibility in data modeling.  OODBMSs are databases designed specifically for working with object-oriented values. Using an OODBMS eliminates the need for converting data to and from its SQL form, as the data is stored in its original object representation and relationships are directly represented, rather than requiring [[junction table|join tables]]/operations. The equivalent of ORMs for [[document-oriented database]]s are called object-document mappers (ODMs).&lt;br /&gt;
&lt;br /&gt;
Document-oriented databases also prevent the user from having to &amp;quot;shred&amp;quot; objects into table rows.  Many of these systems also support the [[XQuery]] query language to retrieve datasets.&lt;br /&gt;
&lt;br /&gt;
Object-oriented databases tend to be used in complex, niche applications. One of the arguments against using an OODBMS is that it may not be able to execute ad-hoc, application-independent queries.{{Citation needed|date=September 2013}} For this reason, many programmers find themselves more at home with an object-SQL mapping system, even though most object-oriented databases are able to process SQL queries to a limited extent. Other OODBMS provide replication to SQL databases, as a means of addressing the need for ad-hoc queries, while preserving well-known query patterns.{{Citation needed|date=September 2018}}&lt;br /&gt;
&lt;br /&gt;
==Challenges==&lt;br /&gt;
A variety of difficulties arise when considering how to match an object system to a relational database. These difficulties are referred to as the [[object–relational impedance mismatch]].&amp;lt;ref&amp;gt;[https://www.semanticscholar.org/paper/Object-Relational-Mapping-Revisited-A-Quantitative-Lorenz-Rudolph/708ac5e798b7e45b949d42e2f872549a3612e1e2 Object–Relational Mapping Revisited - A Quantitative Study on the Impact of Database Technology on O/R Mapping Strategies. M Lorenz, JP Rudolph, G Hesse, M Uflacker, H Plattner. Hawaii International Conference on System Sciences (HICSS), 4877-4886] (DOI:10.24251/hicss.2017.592)&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
An alternative to implementing ORM is use of the native procedural languages provided with every major database. These can be called from the client using SQL statements. The [[Data access object|Data Access Object]] (DAO) design pattern is used to abstract these statements and offer a lightweight object-oriented interface to the rest of the application.&amp;lt;ref&amp;gt;{{cite web |last=Feuerstein |first=Steven |author2=Bill Pribyl |date=September 1997 |title=Oracle PL/SQL Programming |url=http://docstore.mik.ua/orelly/oracle/prog2/ch18_05.htm |access-date=23 August 2011 |language=en-US |location=18.5 Modifying Persistent Objects}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
ORMs are limited to their predefined functionality, which may not cover all edge cases or database features. They usually mitigate this limitation by providing users with an interface to write raw queries, such as Django ORM.&amp;lt;ref&amp;gt;{{Cite web |title=Performing raw SQL queries {{!}} Django documentation |url=https://docs.djangoproject.com/en/5.1/topics/db/sql/ |access-date=2024-09-08 |website=Django Project |language=en}}&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
== See also ==&lt;br /&gt;
*[[List of object–relational mapping software]]&lt;br /&gt;
*[[Comparison of object–relational mapping software]]&lt;br /&gt;
*[[AutoFetch]] – automatic query tuning&lt;br /&gt;
*[[Common Object Request Broker Architecture]] (CORBA)&lt;br /&gt;
*[[Object database]]&lt;br /&gt;
*[[Object persistence]]&lt;br /&gt;
*[[Object–relational database]]&lt;br /&gt;
*[[Object–relational impedance mismatch]]&lt;br /&gt;
*[[Relational model]]&lt;br /&gt;
**[[SQL]] (Structured Query Language)&lt;br /&gt;
*[[Java Data Objects]] (JDO)&lt;br /&gt;
*[[Java Persistence API]] (JPA), now [[Jakarta Persistence]]&lt;br /&gt;
*[[Service Data Objects]]&lt;br /&gt;
*[[Entity Framework]]&lt;br /&gt;
*[[Active record pattern]]&lt;br /&gt;
*[[Data mapper pattern]]&lt;br /&gt;
*[[Single Table Inheritance]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
{{Reflist}}&lt;br /&gt;
&lt;br /&gt;
==External links==&lt;br /&gt;
*[http://www.artima.com/intv/abstract3.html About ORM] by [[Anders Hejlsberg]]&lt;br /&gt;
*[http://www.agiledata.org/essays/mappingObjects.html Mapping Objects to Relational Databases: O/R Mapping In Detail] by [[Scott W. Ambler]]&lt;br /&gt;
&lt;br /&gt;
{{Database}}&lt;br /&gt;
&lt;br /&gt;
{{DEFAULTSORT:Object-Relational Mapping}}&lt;br /&gt;
[[Category:Object–relational mapping| ]]&lt;br /&gt;
[[Category:Data mapping]]&lt;br /&gt;
[[Category:Articles with example C Sharp code]]&lt;/div&gt;</summary>
		<author><name>2605:8D80:6A21:9026:886A:BD7C:FA60:99CB</name></author>
	</entry>
</feed>