The Essence of the Flyweight Design Pattern
In 1998, Palsberg and Jay published a paper on the "Essence of the Visitor Pattern." Their approach to implementing visitors was able to achieve elegance without sacrificing efficiency. To pay homage to that work, this paper, 26 years later, discusses the essential characteristics of another design pattern: the Flyweight. This design pattern describes how to minimize memory usage when storing objects by sharing some of these objects' data with other similar objects. In this paper, we propose that, fundamentally, Flyweights can be incorporated as a built-in feature of programming languages that support the safe memoization of object constructors. Safety, in this context, ensures that the state of an object is not unintentionally altered due to implicit aliasing created by memoization. As a proof of concept, we have implemented our interpretation of the flyweight pattern as a native feature of the Hush programming language. By marking functions that create objects to be memoized, we demonstrate how the flyweight technique naturally emerges. The key to correctness is the use of shared-ownership pointers to reference memoized objects. This approach ensures that mutation of memoized objects causes their removal from the memoization cache. Our implementation incurs minimal performance overhead, as experiments indicate: attributes of memoized objects are accessed with one extra level of indirection, while attributes of non-memoized objects are accessed as in the original implementation of Hush.
Authors
- Fernando Magno Quintão Pereira (ORCID: https://orcid.org/0000-0002-0375-1657)
- Caio Raposo
Institutions
- Universidade Federal de Minas Gerais (BR)
Publication Details
- Published
- 2024-10-17
- DOI
- https://doi.org/10.1145/3694848.3694855
- Primary Topic
- Software Engineering and Design Patterns
- Type
- article
- Field-Weighted Citation Impact
- 0.00