Python Flyweight Pattern
The flyweight pattern is a structural design pattern that minimizes memory usage and improves performance by sharing objects. Simply put, it is the idea of "sharing metadata".
Imagine you go to a library to borrow a book: if every book were purchased separately by different people, the library would need to store thousands of identical copies. But in reality, the library only needs to store one copy of "Python Basics", and everyone who wants to read it can borrow the same copy. The flyweight pattern is like such a "library" - it manages shareable objects.
Core idea
The flyweight pattern divides an object's state into two types:
- Intrinsic State (Internal State): The unchanging, shareable part
- Extrinsic State (External State): The changing, non-shareable part
By sharing intrinsic state, it avoids creating large numbers of similar objects, thus saving system resources.
Why Do We Need the Flyweight Pattern
Problem Scenario
Suppose we are developing a word processor and need to render the characters in a document. If an independent object is created for every character:
Example
Bad implementation: Every character is an independent object
class
Character:
def
init
(
self
,
char
,
font
,
size
,
color
)
:
self
.
char
=
char
Character
self
.
font
=
font
Font
self
.
size
=
size
Font size
self
.
color
=
color
Color
def
render
(
self
,
position
)
:
(
f
"Rendering character '{self.char}' at position {position}"
)
Usage examples
char_a
=
Character
(
'A'
,
'SimSun'
,
12
,
'Black'
)
char_b
=
Character
(
'B'
,
'SimSun'
,
12
,
'Black'
)
char_a_another
=
Character
(
'A'
,
'SimSun'
,
12
,
'Black'
)
Repeatedly creating the same 'A'
Problems with this implementation:
- Memory waste: Identical characters are repeatedly created
- Poor performance: Overhead from creating and destroying large numbers of objects
- Hard to maintain: The number of objects grows explosively
Solution
Using the flyweight pattern, we can:
- Share the same character objects
- Store only one copy of the intrinsic state (the character itself)
- Pass the extrinsic state (position) in at render time
Implementation of the Flyweight Pattern
Basic structure
Let's implement the flyweight pattern using the word processor example:
Example
from
typing
import
Dict
Flyweight Class - Storing Intrinsic State
class
CharacterFlyweight:
def
init
(
self
,
char:
str
,
font:
str
,
size:
int
,
color:
str
)
:
self
.
char
=
char
Intrinsic state: Character content
self
.
font
=
font
Intrinsic state: Font
self
.
size
=
size
Intrinsic state: Font size
self
.
color
=
color
Intrinsic state: Color
def
render
(
self
,
position:
tuple
)
:
"""Render a character; position is the extrinsic state"""
x
,
y
=
position
(
f
"Rendering at position ({x}, {y}): character '{self.char}' "
f
"[font:{self.font}, size:{self.size}, color:{self.color}]"
)
Flyweight Factory - Managing Shared Objects
class
CharacterFactory:
_characters: Dict
[
str
,
CharacterFlyweight
]
=
{
}
@
classmethod
def
get_character
(
cls
,
char:
str
,
font:
str
,
size:
int
,
color:
str
)
CharacterFlyweight:
Creating a unique key for an object
key
=
f
"{char}{font}{size}_{color}"
If the object does not exist, create and cache it
if
key
not
in
cls._characters:
cls._characters
[
key
]
=
CharacterFlyweight
(
char
,
font
,
size
,
color
)
(
f
"Creating new character object: {key}"
)
else
:
(
f
"Reusing existing character object: {key}"
)
return
cls._characters
[
key
]
Client Class - Using Flyweight Objects
class
TextDocument:
def
init
(
self
)
:
self
.
characters
=
[
]
Storing character and position information
def
add_character
(
self
,
char:
str
,
font:
str
,
size:
int
,
color:
str
,
position:
tuple
)
:
Getting a flyweight object from the factory
character
=
CharacterFactory.
get_character
(
char
,
font
,
size
,
color
)
Storing the character object and extrinsic state (position)
self
.
characters
.
append
(
(
character
,
position
)
)
def
render
(
self
)
:
(
"\n=== Starting document rendering ==="
)
for
character
,
position
in
self
.
characters
:
character.
render
(
position
)
(
"=== Document rendering complete ===\n"
)
Usage examples
Example
Create a document
document
=
TextDocument
(
)
Add characters to the document
document.
add_character
(
'H'
,
'Arial'
,
12
,
'black'
,
(
0
,
0
)
)
document.
add_character
(
'e'
,
'Arial'
,
12
,
'black'
,
(
1
,
0
)
)
document.
add_character
(
'l'
,
'Arial'
,
12
,
'black'
,
(
2
,
0
)
)
document.
add_character
(
'l'
,
'Arial'
,
12
,
'black'
,
(
3
,
0
)
)
Reusing 'l'
document.
add_character
(
'o'
,
'Arial'
,
12
,
'black'
,
(
4
,
0
)
)
document.
add_character
(
'!'
,
'Arial'
,
12
,
'red'
,
(
5
,
0
)
)
Different color, creating a new object
document.
add_character
(
'H'
,
'Arial'
,
12
,
'black'
,
(
0
,
1
)
)
Reusing 'H'
Render the document
document.
render
(
)
Check the number of objects in the factory
(
f
"A total of {len(CharacterFactory._characters)} character objects were created in the factory"
)
Output result:
创建新字符对象: H_Arial_12_black
创建新字符对象: e_Arial_12_black
创建新字符对象: l_Arial_12_black
重用现有字符对象: l_Arial_12_black
创建新字符对象: o_Arial_12_black
创建新字符对象: !_Arial_12_red
重用现有字符对象: H_Arial_12_black
=== 开始渲染文档 ===
在位置(0, 0)渲染: 字符'H' [字体:Arial, 大小:12, 颜色:black]
在位置(1, 0)渲染: 字符'e' [字体:Arial, 大小:12, 颜色:black]
在位置(2, 0)渲染: 字符'l' [字体:Arial, 大小:12, 颜色:black]
在位置(3, 0)渲染: 字符'l' [字体:Arial, 大小:12, 颜色:black]
在位置(4, 0)渲染: 字符'o' [字体:Arial, 大小:12, 颜色:black]
在位置(5, 0)渲染: 字符'!' [字体:Arial, 大小:12, 颜色:red]
在位置(0, 1)渲染: 字符'H' [字体:Arial, 大小:12, 颜色:black]
=== 文档渲染完成 ===
工厂中总共创建了 6 个字符对象
Core Components of the Flyweight Pattern
1. Flyweight (Flyweight Interface or Abstract Class)
Defines the interface for flyweight objects, usually including methods that operate on extrinsic state.
2. ConcreteFlyweight (Concrete Flyweight Class)
Implements the flyweight interface and stores intrinsic state. Intrinsic state must be immutable.
3. FlyweightFactory (Flyweight Factory)
Creates and manages flyweight objects, ensuring they are shared correctly.
4. Client
Maintains extrinsic state and requests flyweight objects from the flyweight factory when needed.
A More Complex Example: Application in Game Development
Let's look at a practical example in game development - a tree rendering system:
Example
from
typing
import
Dict
,
List
from
dataclasses
import
dataclass
@
dataclass
class
TreeType:
"""Flyweight class - Tree type (intrinsic state)"""
name:
str
Tree species name
texture:
str
Texture file
color:
str
Base color
def
render
(
self
,
x:
int
,
y:
int
,
height:
int
)
:
"""Render a tree; position and height are extrinsic state"""
(
f
"Rendering a {self.name} tree at ({x}, {y}), height {height} meters "
f
"[texture:{self.texture}, color:{self.color}]"
)
class
TreeFactory:
"""Flyweight factory - Managing tree types"""
_tree_types: Dict
[
str
,
TreeType
]
=
{
}
@
classmethod
def
get_tree_type
(
cls
,
name:
str
,
texture:
str
,
color:
str
)
TreeType:
key
=
f
"{name}{texture}{color}"
if
key
not
in
cls._tree_types:
cls._tree_types
[
key
]
=
TreeType
(
name
,
texture
,
color
)
(
f
"Creating new tree type: {name}"
)
return
cls._tree_types
[
key
]
@
classmethod
def
list_tree_types
(
cls
)
:
(
f
"\nThere are currently {len(cls._tree_types)} tree types:"
)
for
tree_type
in
cls._tree_types.
values
(
)
:
(
f
" - {tree_type.name}"
)
class
Tree:
"""Tree object - Containing a flyweight reference and extrinsic state"""
def
init
(
self
,
x:
int
,
y:
int
,
height:
int
,
tree_type: TreeType
)
:
self
.
x
=
x
Extrinsic state: X coordinate
self
.
y
=
y
Extrinsic state: Y coordinate
self
.
height
=
height
Extrinsic state: Height
self
.
tree_type
=
tree_type
Flyweight object reference
def
render
(
self
)
:
self
.
tree_type
.
render
(
self
.
x
,
self
.
y
,
self
.
height
)
class
Forest:
"""Forest - Client class"""
def
init
(
self
)
:
self
.
trees
: List
[
Tree
]
=
[
]
def
plant_tree
(
self
,
x:
int
,
y:
int
,
height:
int
,
name:
str
,
texture:
str
,
color:
str
)
:
tree_type
=
TreeFactory.
get_tree_type
(
name
,
texture
,
color
)
tree
=
Tree
(
x
,
y
,
height
,
tree_type
)
self
.
trees
.
append
(
tree
)
def
render
(
self
)
:
(
"\n=== Starting forest rendering ==="
)
for
tree
in
self
.
trees
:
tree.
render
(
)
(
"=== Forest rendering complete ==="
)
Usage examples
forest
=
Forest
(
)
Planting trees - Trees of the same type share flyweight objects
forest.
plant_tree
(
10
,
20
,
15
,
"Pine tree"
,
"pine_texture.png"
,
"Dark green"
)
forest.
plant_tree
(
30
,
40
,
12
,
"Pine tree"
,
"pine_texture.png"
,
"Dark green"
)
Reusing the pine tree type
forest.
plant_tree
(
50
,
60
,
18
,
"Oak tree"
,
"oak_texture.png"
,
"Light green"
)
forest.
plant_tree
(
70
,
80
,
20
,
"Pine tree"
,
"pine_texture.png"
,
"Dark green"
)
Reusing again
forest.
plant_tree
(
90
,
100
,
16
,
"Maple tree"
,
"maple_texture.png"
,
"Red"
)
Render the forest
forest.
render
(
)
View tree type statistics
TreeFactory.
list_tree_types
(
)
Advantages and Disadvantages of the Flyweight Pattern
Advantages
- Greatly reduces memory usage: Significantly lowers memory usage by sharing similar objects
- Improves performance: Reduces the overhead of object creation and garbage collection
- Code Reuse: The same object logic only needs to be implemented once
- Easy to extend: Adding new flyweight types does not affect existing code
Disadvantages
- Increased complexity: Requires distinguishing intrinsic state from extrinsic state
- Thread safety issues: Shared objects require extra handling in multi-threaded environments
- May introduce bugs: If intrinsic state is modified incorrectly, all users are affected
- Not suitable for all scenarios: Only effective when objects are truly shareable
Applicable scenarios
Scenarios Suitable for the Flyweight Pattern
- Large numbers of similar objects: When the system needs to create large numbers of similar objects
- Memory-sensitive applications: Memory-constrained environments such as mobile devices and embedded systems
- Caching system: When objects need to be cached and reused
- Game Development: Rendering large numbers of the same type of game objects
- Document processing: Word processors, spreadsheet processors, etc.
Scenarios Where It Is Not Suitable
- Objects differ greatly: If every object has unique state
- Extrinsic state is complex: If managing extrinsic state is more complex than creating objects
- Performance requirements are low: In scenarios with sufficient memory and low performance requirements
Practical Exercise
Exercise 1: Improve the Character Rendering System
Try to improve our earlier character rendering system by adding support for styles such as bold and italic:
Example
Your improved code goes here
class
AdvancedCharacterFlyweight:
Add support for bold, italic, and underline
pass
Test your implementation
def
test_advanced_system
(
)
:
Create a document containing different styles
pass
Exercise 2: Implement an Icon Management System
Design an icon management system where the same icon shares one object when displayed at different positions:
Example
class
IconFlyweight:
Store intrinsic state such as icon file path and size
pass
class
IconFactory:
Manage icon flyweight objects
pass
class
Application:
Display icons at different positions in the interface
pass
Summary
The flyweight pattern is a powerful optimization technique that reduces resource consumption by sharing objects. Key points:
- Distinguish states: Clearly distinguish intrinsic state (shareable) from extrinsic state (non-shareable)
- Use a factory: Manage the creation and sharing of flyweight objects through a factory class
- Weigh the pros and cons: Find a balance between memory savings and code complexity
- Applicable scenarios: Mainly used in scenarios with large numbers of similar objects