zoukankan      html  css  js  c++  java
  • 享元模式(flyweight)

    定义:

    • 以共享的方式高效地支持大量细粒度对象的重用

    核心:

    • 享元对象能做到共享的关建是区分了内部状态和外部状态。

      • 内部状态:可以共享,不会随环境变化而变化

      • 外部状态:不可以共享,会随环境变化而改变

    例如我们要在森林中种树

    package designmode.flyweight;
    public class Tree {
    
        private final String name;
        private final String data;
    
        public String getName() {
            return name;
        }
    
        public String getData() {
            return data;
        }
        public Tree(String name, String data) {
            System.out.printf("%s创建成功",name);
            this.name = name;
            this.data = data;
        }
    }
    package designmode.flyweight;
    public class TreeNode {
        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;
        }
    
        public TreeNode(int x, int y, Tree tree) {
            super();
            this.x = x;
            this.y = y;
            this.tree = tree;
        }
        private int x;
        private int y;
        private Tree tree;
    }
    package designmode.flyweight;
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;
    public 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;
        }
    }
    package designmode.flyweight;
    public class Client {
        public static void main(String[] args) {
            TreeNode node = new TreeNode(12,23,TreeFactory.getTree("松树", "30年的松树"));
            TreeNode node1 = new TreeNode(2,12,TreeFactory.getTree("松树", "20年的树"));
        }
    }

    享元模式实现:

    • FlyweightFactory享元工厂类:

      • 创建并管理享元对象,享元池一般设计成键值对

      • FlyWeight抽象享元类:

      • 通常是一个接口或抽象类,声明公共方法,这些方法可以向外界提供对象的内部状态,设置外部状态。

      • ConcreteFlyWeight具体享元类:

      • 为内部状态提供成员变量进行存储

      • UnsharedConccreteFlyWeight非共享享元类:

      • 不能被共享的子类可以设计为非共享享元类





  • 相关阅读:
    解决SharePoint 文档库itemadded eventhandler导致的上传完成后,编辑页面保持报错的问题,错误信息为“该文档已经被编辑过 the file has been modified by...”
    解决SharePoint 2013 designer workflow 在发布的报错“负载平衡没有设置”The workflow files were saved but cannot be run.
    随机实例,随机值
    Spring4笔记
    struts2笔记(3)
    struts2笔记(2)
    获取文本的编码类型(from logparse)
    FileUtil(from logparser)
    DateUtil(SimpleDateFormat)
    struts2笔记
  • 原文地址:https://www.cnblogs.com/baiyifengyun/p/14409401.html
Copyright © 2011-2022 走看看