Flyweight pattern is to help re-use created object if the object is fine-grained and the key parameter is not changed, in this case we can avoid to waste memory.
The parameters can be sperate to 2 parts, first part is internal parameters, like key parameter; the second parts are parameters which can be assigned from outside.
The implementation way is, we create a map to record the objects we have created based on key parameter, next time if we create new object with same key , we will not create it but directly ask for map to return, the other parameters we will assign values from outside.
Below example is we will create many tree nodes on the map, but which type of the tree is will be part of internal parameter, tree location are parameters assigned from outside like when we initial the map.
public Tree createTree(String type) {
if (treeMap.containsKey(type)){
return treeMap.get(type);
}
Tree tree = new Tree(type);
treeMap.put(type, tree);
System.out.println("Create new tree object");
return tree;
}
When we initial the map, we can create tree node objects, but insde, whether we create new tree we will base on whether tree key parameter is changed or not. In below example, we only create 2 tree objects, even though we will have 20 tree node objects.
String type = "normal";
TreeFactory factory = new TreeFactory();
for (int i = 0; i < 10; i++) {
int x = (int) (Math.random() * 100);
int y = (int) (Math.random() * 100);
TreeNode treenote = new TreeNode(x, y, factory.createTree(type));
System.out.println(treenote);
}
type = "tall";
for (int j = 0; j < 10; j++) {
int x = (int) (Math.random() * 100);
int y = (int) (Math.random() * 100);
TreeNode treenote = new TreeNode(x, y, factory.createTree(type));
System.out.println(treenote);
}