享元模式
模式定义:运用共享技术有效地支持大量细粒度的对象。
优点:如果系统有大量类似的对象,可以节省大量的内存及CPU资源。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| class TreeNode{ private int x; private int y; private Tree tree; public TreeNode(int x, int y, Tree tree) { this.x = x; this.y = y; this.tree = tree; } public int getX() { return x; } public int getY() { return y; } public Tree getTree() { return tree; } }
class Tree{ private final String name; private final String data; public Tree(String name, String data) { System.out.println("name:"+name+"tree created. "); this.name = name; this.data = data; } public String getName() { return name; } public String getData() { return data; } }
class TreeFactory{ private static Map<String,Tree> map = new ConcurrentHashMap<>(); public static Tree getTree(String name,String data){ if (map.containsKey(name)){ return map.get(name); } Tree tree = new Tree(name, data); map.put(name,tree); return tree; } }
|
JDK源码中的应用:
1 2
| String,Integer,Long... com.sun.org.apache.bcel.internal.generic.InstructionConstants;
|