# Purpose
The Flyweight pattern is based on the idea of sharing objects that are repeated, instead of creating a new instance for each one.
This optimizes memory usage since it eliminates the redundancy of objects with identical properties.
# Problem
Excessive memory usage and overload due to creating a huge number of objects that have almost the same state (redundancy).
# Solution
The solution proposed by the Flyweight is:
-
Data Separation: Stores common data (intrinsic) in flyweights and passes specific data (extrinsic) via methods.
-
Reuse: Allows objects to be used in different contexts avoiding creation of new ones.
# Structure
# Participants
- Flyweight: Interface to receive extrinsic state.
- ConcreteFlyweight: Stores intrinsic state (shared).
- UnsharedConcreteFlyweight: Stores extrinsic state.
- FlyweightFactory: Manages and ensures sharing.
- Client: Maintains references and computes extrinsic states.
# When to Use It
-
A huge number of objects with similar states that can be shared.
-
Critical need to reduce memory footprint.
# Advantages
-
verified
Memory Efficiency: Significantly reduces usage.
-
verified
Better Performance: Especially in constrained systems.
# Disadvantages
-
warning
Complexity: More difficult design to implement.
-
warning
CPU Overhead: Handling extrinsic states might cost processing time.
# Example: Chess Game
We efficiently manage the board pieces. Many pieces (pawns) share the same color but have different positions.
# Java Code
class ChessPieceFactory {
private static final Map PIECES = new HashMap<>();
public static ChessPiece getChessPiece(String color) {
PIECES.computeIfAbsent(color, c -> new Pawn(c));
return PIECES.get(color);
}
}
class Pawn implements ChessPiece {
private String color; // intrinsic
public void draw(Position pos) { // pos: extrinsic
System.out.println("Pawn " + color + " at " + pos);
}
}
# Mapping Participants
- ChessPiece (Flyweight): Common interface.
- Pawn (ConcreteFlyweight): Stores color.
- Position (Unshared): x,y coordinates.
- ChessPieceFactory (Factory): Reuses instances.
# Conclusions
Allows efficient memory usage and improves performance by sharing common pieces while keeping the specific state of each one separate.
# Related Patterns
Composite
Can be combined to implement hierarchical logical structures.
State and Strategy
Are often best implemented as flyweights.