1.享元模式(Flyweight)定义:运用共享技术有效地支持大量细粒度的对象

  1. class Tree{
  2. private final String name; //final初始后不可再变化,避免多线程下数据安全问题
  3. private final String data; //final初始后不可再变化,避免多线程下数据安全问题
  4. public Tree(String name,String data){
  5. this.name = name;
  6. this.data = data;
  7. System.out.println(name+" created");
  8. }
  9. }
  10. class TreeInstance{
  11. public int x;
  12. public int y;
  13. public Tree tree;
  14. public TreeInstance(int x,int y,Tree tree){
  15. this.x = x;
  16. this.y = y;
  17. this.tree = tree;
  18. }
  19. }
  20. class TreeFactory{
  21. public static Map<String,Tree> mapTree = new ConcurrentHashMap<>();
  22. public static Tree getTree(String treeName,String data){
  23. if(mapTree.containsKey(treeName)){
  24. return mapTree.get(treeName);
  25. }
  26. Tree tree = new Tree(treeName,data);
  27. mapTree.put(treeName,tree);
  28. return tree;
  29. }
  30. }
  31. public class Flyweight {
  32. public static void main(String[] args) {
  33. //在位置点6,8种一棵tree1树
  34. TreeInstance treeInstance1 = new TreeInstance(6,8,TreeFactory.getTree("tree1","data1"));
  35. //在位置点10,18种一棵tree1树,此时会返回一棵相同的树,即treeNode1和treeNode2共享一颗同样的树,只是位置不一样,如游戏场景下可以节省很多相同的树创建多个相同的对象,节省内存空间
  36. TreeInstance treeInstance2 = new TreeInstance(10,18,TreeFactory.getTree("tree1","data1"));
  37. //当然这里也可以创建其它类型的树,并传入树的相关data信息
  38. TreeInstance treeInstance3 = new TreeInstance(20,28,TreeFactory.getTree("tree2","data2"));
  39. }
  40. }

image.png

应用场景:
大量的重复对象使用

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

JDK源码中的应用
1String,Integer,Long…
2com.sun.org.apache.bcel.internal.generic.InstructionConstants