享元(Flyweight)模式

享元(Flyweight)模式

模式定义:运用共享技术有效地支持大量细粒度的对象。

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

缺点:

  1. 为了使对象可以共享,需要将一些不能共享的状态外部化,这将增加程序的复杂性。
  2. 读取享元模式的外部状态会使得运行时间稍微变长。

数据共享要考虑的问题:多线程

  • 数据一致性
  • 不可变对象[String ]
package flyweight;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class FlyWeightTest {
    public static void main(String[] args) {

        TreeNode tree1 = new TreeNode(3, 4, TreeFactory.getTree("name1","tree1"));
        TreeNode tree2 = new TreeNode(5, 4, TreeFactory.getTree("name1","tree2"));
        TreeNode tree3 = new TreeNode(13, 4, TreeFactory.getTree("name1","tree2"));
        TreeNode tree4 = new TreeNode(3, 5, TreeFactory.getTree("name1","tree2"));
        //只会创建一个树,来共享
    }
}

/**
 * 定义放置树的坐标
 */
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 void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void setTree(Tree tree) {
        this.tree = 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){

        //如果存在name的key,则直接返回这个key为name的对象,否则就创建
        if(map.containsKey(name)){
            return map.get(name);
        }
        Tree tree = new Tree(name,data);
        map.put(name,tree);
        return tree;
    }
}

posted @ 2020-07-29 22:45  Noob52037  阅读(107)  评论(0编辑  收藏  举报