设计模式-享元模式

享元模式

定义:运用共享技术有效地支持大量细粒度的对象

优点:如果系统有大量类似的对象,可以节省大量的内存和CPU资源

实现

场景:假如我要开发一款游戏,然后游戏里面的地图有很多树木

这个时候,我们不可能创建几万个树的对象

Tree

1
2
3
4
5
6
@Data
@AllArgsConstructor
@ToString
public class Tree {
private final String name;
}

TreeNode

1
2
3
4
5
6
7
@Data
@AllArgsConstructor
public class TreeNode {
private final Tree tree;
private int x;
private int y;
}

TreeFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
public class TreeFactory {
private static ConcurrentHashMap<String, Tree> map = new ConcurrentHashMap<>();
public static Tree getTree(String name){
if(map.containsKey(name)){
return map.get(name);
}
return null;
}

public static void addTree(String name){
map.put(name,new Tree(name));
}
}

主函数

1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
TreeFactory.addTree("梧桐树");
TreeFactory.addTree("香樟树");
TreeFactory.addTree("银杏树");
TreeFactory.addTree("面包树");
TreeNode treeNode1 = new TreeNode(TreeFactory.getTree("梧桐树"),1,1);
TreeNode treeNode2 = new TreeNode(TreeFactory.getTree("梧桐树"),1,2);
TreeNode treeNode3 = new TreeNode(TreeFactory.getTree("梧桐树"),1,3);
}
给作者买杯咖啡吧~~~