Add all 23 GoF design pattern implementations (2026-06-13)
This commit is contained in:
29
02-structural/flyweight/TreeFactory.java
Normal file
29
02-structural/flyweight/TreeFactory.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package flyweight;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Flyweight Factory — the cache that ensures each unique TreeType
|
||||
* is only created once, no matter how many trees use it.
|
||||
*
|
||||
* This is the piece that makes Flyweight work:
|
||||
* it intercepts creation requests and returns an existing
|
||||
* shared instance if one already exists.
|
||||
*/
|
||||
public class TreeFactory {
|
||||
|
||||
// The pool of shared flyweights
|
||||
private static final Map<String, TreeType> treeTypes = new HashMap<>();
|
||||
|
||||
public static TreeType getTreeType(String name, String color, String texture) {
|
||||
String key = name + "_" + color + "_" + texture;
|
||||
|
||||
// Only create a new TreeType if we haven't seen this combination before
|
||||
return treeTypes.computeIfAbsent(key, k -> new TreeType(name, color, texture));
|
||||
}
|
||||
|
||||
public static int getPoolSize() {
|
||||
return treeTypes.size();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user