享元模式

2022-05-05 16:57:58 浏览数 (1)

享元模式

模式定义

运用共享技术有效的支持大量粒度的对象

优点

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

实现
代码语言:javascript复制
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 需求:
 * 在一张游戏地图中有无数的树,那么是不是每一颗树都是一个对象呢?
 * 显然不是!不同种类的树是不同的对象,同一种类的树是一个对象
 * 只是一些属性不同而已
 */
public class FlyWeightTest {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(3, 4, TreeFactory.getTree("xxx", "xxxxx"));
        TreeNode treeNode1 = new TreeNode(8, 4, TreeFactory.getTree("xxx", "xxxxx"));
        TreeNode treeNode3 = new TreeNode(6, 4, TreeFactory.getTree("yyy", "xxxxx"));
        TreeNode treeNode4 = new TreeNode(5, 4, TreeFactory.getTree("yyy", "xxxxx"));
    }
}
//树节点信息
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 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;
    }
}
//工厂产生树
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;
    }
}
//树对象
class Tree{
    private final String name;
    private final String data;

    public Tree(String name, String data) {
        System.out.println(name "树产生");
        this.name = name;
        this.data = data;
    }

    public String getName() {
        return name;
    }

    public String getData() {
        return data;
    }
}

0 人点赞