In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory usage by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the objects temporarily when they are used.
A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally.
Another example is string interning.
In other contexts the idea of sharing identical data structures is called hash consing.
Video Flyweight pattern
Overview
The Flyweight design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
What problems can the Flyweight design pattern solve?
- Large numbers of objects should be supported efficiently.
- Creating large numbers of objects should be avoided.
When representing large text documents, for example, creating an object for each character in the document would result in a huge amount of objects that couldn't be processed efficiently.
What solution does the Flyweight design pattern describe?
Define Flyweight
objects that
- store intrinsic (invariant) state that can be shared and
- provide an interface through which extrinsic (variant) state can be passed in.
This enables clients to (1) reuse (share) Flyweight
objects (instead of creating a new object each time) and (2) pass in extrinsic state when they invoke a Flyweight
operation.
This greatly reduces the number of physically created objects.
Intrinsic state is invariant (context independent) and therefore can be shared (for example, the code of character 'A' in a given character set).
Extrinsic state is variant (context dependent) and therefore can not be shared and must be passed in (for example, the position of character 'A' in a text document).
See also the UML class and sequence diagram below.
Maps Flyweight pattern
History
According to the textbook Design Patterns: Elements of Reusable Object-Oriented Software, the flyweight pattern was first coined and extensively explored by Paul Calder and Mark Linton in 1990 to efficiently handle glyph information in a WYSIWYG document editor, although similar techniques were already used in other systems, e.g., an application framework by Weinand et al. (1988).
Structure
UML class and sequence diagram
In the above UML class diagram, the Client
class refers (1) to the FlyweightFactory
class to create/share Flyweight
objects and (2) to the Flyweight
interface to perform an operation by passing in extrinsic (variant) state (flyweight.operation(extrinsicState)
). The Flyweight1
class implements the Flyweight
interface and stores intrinsic (invariant) state that can be shared.
The sequence diagram shows the run-time interactions: The Client
object calls getFlyweight(key)
on the FlyweightFactory
that creates and returns a Flyweight1
object. After calling operation(extrinsicState)
on the returned Flyweight1
object, the Client
again calls getFlyweight(key)
on the FlyweightFactory
, which now shares and returns the already existing Flyweight1
object.
Immutability and equality
To enable safe sharing, between clients and threads, Flyweight objects must be immutable. Flyweight objects are by definition value objects. The identity of the object instance is of no consequence therefore two Flyweight instances of the same value are considered equal.
Example in C# (note Equals and GetHashCode overrides as well as == and != operator overloads):
Concurrency
Special consideration must be made in scenarios 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. This option is only viable if the equality criterion is met.
Example in C#
Simple implementation
Flyweight allows you to share bulky data that are common to each object. In other words, if you think that same data is repeating for every object, you can use this pattern to point to the single object and hence can easily save space. Here the FlyweightPointer creates a static member Company, which is used for every object of MyObject.
Example in Java
The execution of this code will give the following :
For this example of code the invariant part are the BMW Serie 1 & 2 cars witch are Fly weight objects, the variant parts are passed throw an operation, for this example we doesn't need to create a car for each customer need and specification witch can be troublesome for all customization possibilities, the customization witch is the variant part have an object that is only needed for calculation and printing.
Example in Scala
Example in Ruby
Example in Python
Attributes can be defined at the class-level instead of only for instances in Python because classes are first-class objects in the language--meaning there are no restrictions on their use as they are the same as any other object. New-style class instances store instance data in a special attribute dictionary instance.__dict__
. By default, accessed attributes are first looked-up in this __dict__
, and then fallback to the instance's class attributes next. In this way, a class can effectively be a kind of Flyweight container for its instances.
Although Python classes are mutable by default, immutability can be emulated by overriding the class's __setattr__
method so that it disallows changes to any Flyweight attributes.
Example in Swift
Example in Crystal
Output
Serving Cappuchino to table 2 Serving Frappe to table 1 Serving Espresso to table 1 Serving Frappe to table 897 Serving Cappuccino to table 97 Serving Frappe to table 3 Serving Espresso to table 3 Serving Cappuccino to table 3 Serving Espresso to table 96 Serving Frappe to table 552 Serving Cappuccino to table 121 Serving Espresso to table 121 Total CoffeeFlavor made: 4
See also
- Copy-on-write
- Memoization
- Multiton
References
Source of the article : Wikipedia