1.享元模式(Flyweight)定义:运用共享技术有效地支持大量细粒度的对象
class Tree{
private final String name; //final初始后不可再变化,避免多线程下数据安全问题
private final String data; //final初始后不可再变化,避免多线程下数据安全问题
public Tree(String name,String data){
this.name = name;
this.data = data;
System.out.println(name+" created");
}
}
class TreeInstance{
public int x;
public int y;
public Tree tree;
public TreeInstance(int x,int y,Tree tree){
this.x = x;
this.y = y;
this.tree = tree;
}
}
class TreeFactory{
public static Map<String,Tree> mapTree = new ConcurrentHashMap<>();
public static Tree getTree(String treeName,String data){
if(mapTree.containsKey(treeName)){
return mapTree.get(treeName);
}
Tree tree = new Tree(treeName,data);
mapTree.put(treeName,tree);
return tree;
}
}
public class Flyweight {
public static void main(String[] args) {
//在位置点6,8种一棵tree1树
TreeInstance treeInstance1 = new TreeInstance(6,8,TreeFactory.getTree("tree1","data1"));
//在位置点10,18种一棵tree1树,此时会返回一棵相同的树,即treeNode1和treeNode2共享一颗同样的树,只是位置不一样,如游戏场景下可以节省很多相同的树创建多个相同的对象,节省内存空间
TreeInstance treeInstance2 = new TreeInstance(10,18,TreeFactory.getTree("tree1","data1"));
//当然这里也可以创建其它类型的树,并传入树的相关data信息
TreeInstance treeInstance3 = new TreeInstance(20,28,TreeFactory.getTree("tree2","data2"));
}
}
应用场景:
大量的重复对象使用
优点:
如果系统有大量类似的对象,可以节省大量的内存及CPU资源
JDK源码中的应用
1String,Integer,Long…
2com.sun.org.apache.bcel.internal.generic.InstructionConstants