function FlyweightFactory(){ var hash = new Hashtable(); } FlyweightFactory.prototype.getFlyweight = function(state) { var flyweight; if (hash.contain(state)) { flyweight = hash.get(state); } else { flyweight = new Flyweight(state); hash.add(state, flyweight); } return flyweight; } FlyweightFactory.prototype.getComposite = function(list) { var unFly = new UnShareFlyweight(); var flyweight, state; for (idx in list) { state = list[idx]; flyweight = this.getFlyweight(state); unFly.add(state, flyweight); } } FlyweightFactory.prototype.print = function() { var jsons = this.hash.getJson(); for (json in jsons) { json.value.operate(); } }
3. Client 使用:
var states = ['AABB', 'CDCD', 'AABB', 'CCDD']; var factory = new FlyweightFactory(); factory.getComposite(states); factory.print();
输出:
AABB-0.8749617566354573
CDCD-0.6991151459515095
CCDD-0.9891050879377872
享元模式其他说明总体来说,享元模式用于减少对象的重复创建,用于减少内存使用,提升性能的结构型模式:
它涉及三个模式:享元模式,工厂模式,组合模式;
对于处理多对多对应而产生的一些数据缓存存储,是一个不错的选择!
感兴趣的朋友可以使用在线HTML/CSS/JavaScript代码运行工具:测试上述代码运行效果。
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《javascript面向对象入门教程》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》