享元模式

这个享元翻译的不是很好,让初接触的不明所以。倒不如它的英文flyweight更直观。

这才发现成天使用的Extjs里面的Ext.fly原来就是这种模式!

参见:

--------------------------------------

Ext.fly = El.fly;
/**
* Gets the globally shared flyweight Element, with the passed node as the active element. Do not store a reference to this element -
* the dom node can be overwritten by other code.
* @param {String/HTMLElement} el The dom node or id
* @param {String} named (optional) Allows for creation of named reusable flyweights to
*                                  prevent conflicts (e.g. internally Ext uses "_internal")
* @static
* @return {Element} The shared Element object (or null if no matching element was found)
*/
El.fly = function(el, named){
    named = named || '_global';
    el = Ext.getDom(el);
    if(!el){
        return null;
    }
    if(!El._flyweights[named]){
        El._flyweights[named] = new El.Flyweight();
    }
    El._flyweights[named].dom = el;
    return El._flyweights[named];
};

---------------------------------

El._flyweights = {};
var flyFn = function(){};
flyFn.prototype = El.prototype;
var _cls = new flyFn();

// dom is optional
El.Flyweight = function(dom){
    this.dom = dom;
};

El.Flyweight.prototype = _cls;
El.Flyweight.prototype.isFlyweight = true;


Total views.

© 2013 - 2024. All rights reserved.

Powered by Hydejack v6.6.1