Files

30 lines
895 B
Java

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();
}
}