ArticleslgStudy

computer science

Flyweight pattern

Flyweight pattern is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Flyweight pattern rather than just read about it. In short: 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.

Flyweight pattern — main illustration
Flyweight pattern — illustration

Key takeaways

  • Flyweight pattern belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Flyweight pattern to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Flyweight pattern from memory before moving on to harder problems.

Reference excerpt

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.

Structure

The above UML class diagram 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 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 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 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 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 value objects, 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.

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.

PHP

See also Copy-on-write Memoization Multiton

References

External links C like performance using flyweight wrappers

Illustrations

Flyweight pattern: Text editors, such as LibreOffice Writer, often use the flyweight pattern.[vague]
Text editors, such as LibreOffice Writer, often use the flyweight pattern.[vague]
Flyweight pattern: A sample UML class and sequence diagram for the Flyweight design pattern.[6]
A sample UML class and sequence diagram for the Flyweight design pattern.[6]

Worked examples

Example 1 — a first encounter with Flyweight pattern

Start with the simplest possible case. Write down what Flyweight pattern claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Flyweight pattern before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Flyweight pattern ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Flyweight pattern

In research
Flyweight pattern appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Flyweight pattern in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Flyweight pattern is common in secondary-school and first-year university syllabi. It links to neighbouring topics Software design patterns, Software optimization, so understanding it makes those chapters shorter.
In everyday life
Look for Flyweight pattern outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Flyweight pattern” →

How to study Flyweight pattern in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Flyweight pattern means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Flyweight pattern out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Flyweight pattern in simple terms?

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.

Why does Flyweight pattern matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Flyweight pattern?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Flyweight pattern.

Tags

  • Software design patterns
  • Software optimization

Keep exploring