Deep Dive into Java Flyweight Pattern: Achieving Efficient Object Sharing and Memory Optimization
The article explains the Flyweight design pattern in Java, detailing intrinsic vs extrinsic state, the role of a FlyweightFactory, step‑by‑step code examples for sharing Circle objects, and discusses its advantages, suitable scenarios, and how it reduces memory usage while boosting performance.
Introduction
Design patterns provide reusable solutions; the Flyweight pattern is a structural pattern that reduces the number of objects by sharing them, thereby lowering resource consumption and improving performance.
Concept of Flyweight
The pattern separates object state into intrinsic (shared) and extrinsic (context‑specific) parts. Intrinsic state, such as font and size in a character rendering system, can be shared, while extrinsic state like position or color cannot.
Object State Division
Intrinsic State : immutable attributes that can be shared across contexts.
Extrinsic State : mutable attributes that depend on the usage context.
Sharing Mechanism
A FlyweightFactory maintains a cache (e.g., a hash map) of created Flyweight objects. When a request arrives, the factory returns an existing instance if the intrinsic state matches; otherwise it creates a new one, stores it, and returns it.
Structure
The pattern consists of three participants:
Flyweight : the shared object (e.g., Circle with intrinsic color).
FlyweightFactory : creates and caches Flyweight instances using a HashMap<String, Circle>.
Client : obtains Flyweight objects from the factory and supplies extrinsic state.
Working Process
Identify and extract intrinsic state.
Separate extrinsic state.
Implement a FlyweightFactory to manage caching.
Client retrieves Flyweight objects and provides extrinsic state during operation.
Implementation Example
Code defines a Circle class with a color field, a CircleFactory that caches circles in a HashMap, and a demo that requests circles of colors “red” and “blue”. The demo shows that two requests for “red” return the same instance (output true).
public class Circle {
private String color; // intrinsic state
public Circle(String color) { this.color = color; }
public void draw() { System.out.println("Draw a " + color + " circle"); }
} public class CircleFactory {
private Map<String, Circle> circleMap = new HashMap<>();
public Circle getCircle(String color) {
Circle circle = circleMap.get(color);
if (circle == null) {
circle = new Circle(color);
circleMap.put(color, circle);
}
return circle;
}
} public class FlyweightPatternDemo {
private static final CircleFactory circleFactory = new CircleFactory();
public static void main(String[] args) {
Circle c1 = circleFactory.getCircle("red");
c1.draw();
Circle c2 = circleFactory.getCircle("blue");
c2.draw();
Circle c3 = circleFactory.getCircle("red");
c3.draw();
System.out.println(c1 == c3); // true
}
}Advantages and Applicable Scenarios
Advantages: reduced memory consumption, improved performance, and simplified system design by separating shared and varying parts.
Suitable when a system must handle large numbers of similar objects, object creation is costly, or resource optimization and performance are critical.
Conclusion
The Flyweight pattern offers an effective way to manage many similar objects by sharing intrinsic state, leading to lower memory usage and higher performance, provided developers correctly identify intrinsic versus extrinsic state and design appropriate factories.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer1970
Formerly called 'Code to 35'. Add our main WeChat ID to access a wealth of shared resources (algorithms, interview prep, tech stacks: Java, Python, Go, big data). We mainly share serious development techniques, focusing on output-driven input. Occasionally we post life snippets and gossip. Our aim is to attract precise traffic and test advertising opportunities.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
