Add all 23 GoF design pattern implementations (2026-06-13)
This commit is contained in:
31
02-structural/flyweight/Tree.java
Normal file
31
02-structural/flyweight/Tree.java
Normal file
@@ -0,0 +1,31 @@
|
||||
package flyweight;
|
||||
|
||||
/**
|
||||
* Context — stores the UNIQUE (extrinsic) state for each tree instance.
|
||||
* This is NOT the flyweight itself; it's the lightweight object that
|
||||
* holds position data and delegates rendering to a shared TreeType.
|
||||
*
|
||||
* 10,000 Tree objects × (x:4 bytes + y:4 bytes + reference:8 bytes) = ~160 KB
|
||||
* vs.
|
||||
* 10,000 Tree objects × (name + color + texture + x + y) = potentially MBs
|
||||
*/
|
||||
public class Tree {
|
||||
|
||||
// Extrinsic (unique) state — different per tree
|
||||
private final int x;
|
||||
private final int y;
|
||||
|
||||
// Reference to the SHARED flyweight
|
||||
private final TreeType type;
|
||||
|
||||
public Tree(int x, int y, TreeType type) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public void draw() {
|
||||
// Passes extrinsic state (position) into the shared flyweight
|
||||
type.draw(x, y);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user