美文网首页Java程序性能优化
设计优化之享元模式

设计优化之享元模式

作者: Chinesszz | 来源:发表于2017-06-04 13:43 被阅读4次
    何为享元模式,大家不要被这个陌生的词汇所吓倒,其实笔者感觉这个是最容易理解的,下面请看笔者分析。
    享元模式:

    所谓享元模式,就是相同对象,在内存中之存在一份,大家都共享着一个实例对象。代码体现上很像工厂模式,通过工厂找到这个对象,如果存在就直接获取,如果不存在就创建同时,保存,方便下次直接获取。以下是代码

    • 定义接口,可以从这个里面获得
    /**
     * Created by mac on 2017/6/4.
     */
    public interface IFlyWeight {
        String getName();
    }
    
    
    • 定义用户实现类
    public class UserFlyWeight implements IFlyWeight {
        public String name;
        public UserFlyWeight(String name){
            this.name=name;
        }
        public String getName() {
            return this.name;
        }
    }
    
    • 具体实现
    /*
     * Created by mac on 2017/6/4.
     */
    public class FlyWightFactory {
    
        Map<String, IFlyWeight> fly = new HashMap<String, IFlyWeight>();
    
        /**
         * 存在就直接返回,不存在就创建保存并返回
         * @param name
         * @return
         */
        public IFlyWeight getFlyWeight(String name) {
            IFlyWeight result = fly.get(name);
            if (result == null) {
                result = new UserFlyWeight(name);
                fly.put(name, result);
            }
            return result;
        }
    }
    
    

    在Flyweight模式中,由于要产生各种各样的对象,所以在Flyweight(享元)模式中常出现Factory模式。Flyweight的内部状态是用来共享的,Flyweight factory负责维护一个对象存储池(Flyweight Pool)来存放内部状态的对象。Flyweight模式是一个提高[程序]效率和性能的模式,会大大加快程序的运行速度.

    • 实验
    public class Main {
        public static void main(String[] args) {
            long start=System.currentTimeMillis();
            for (int i = 0; i < 100000; i++) {
                String name = "A";
                String name2 = "B";
                String name3 = "C";
                FlyWightFactory.getFlyWeight(name).getName();
                FlyWightFactory.getFlyWeight(name2).getName();
                FlyWightFactory.getFlyWeight(name3).getName();
            }
            long end=System.currentTimeMillis();
            System.out.format("耗时:%d,ms,map实例数量:%d",(end-start),FlyWightFactory.fly.size());
          //耗时:63,ms,map实例数量:3
        }
    }
    

    可以看到虽然从里面取了10万次,但是只用了63ms,切对于这些相同对象,内存中之存在唯一的一份

    相关文章

      网友评论

        本文标题:设计优化之享元模式

        本文链接:https://www.haomeiwen.com/subject/qqbvfxtx.html