模式定义:运用共享技术有效地支持大量细粒度的对象
优点:如果系统有大量类似的对象,可以节省大量的内存及CPU资源
public class FlyWeightTest { public static void main(String[] args) { TreeNode treeNode1 = new TreeNode(3, 4, TreeFactory.getTree("xyk", "dashuaige")); TreeNode treeNode2 = new TreeNode(2, 4, TreeFactory.getTree("xyk", "dashuaige")); } } class TreeNode{ private int x; private int y; private Tree tree; public TreeNode() { } public TreeNode(int x, int y, Tree tree) { this.x = x; this.y = y; this.tree = tree; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public Tree getTree() { return tree; } public void setTree(Tree tree) { this.tree = tree; } } //定义一个工厂来产生tree class TreeFactory{ //ConcurrentHashMap线程安全 private static Map<String,Tree> map = new ConcurrentHashMap<>(); public static Tree getTree(String name,String date){ if(map.containsKey(name)==true){ return map.get(name); }else { Tree tree = new Tree(name,date); map.put(name,tree); return tree; } } } //在享元模式下可以让它变成不可变的对象 class Tree{ private final String name; private final String date; public Tree(String name, String date) { System.out.println("创建一个一颗"+name+"的数."); this.name = name; this.date = date; } public String getName() { return name; } public String getDate() { return date; } @Override public String toString() { return "Tree{" + "name='" + name + '\'' + ", date='" + date + '\'' + '}'; } }