PooledClass源码

PooledClass.addPoolingTo(CopyConstructor)用于将构造函数CopyConstructor转化为工厂函数,意义是管理实例数据的创建和销毁,并将销毁数据的实例推入到实例池CopyConstructor.instancePool中。

'use strict';

var _prodInvariant = require('./reactProdInvariant');// 生产环境React形式带url报错

// invariant(condition,format,a,b,c,d,e,f) condition为否值,替换format中的"%s",并throw error报错  
var invariant = require('fbjs/lib/invariant');

// 单参数创建实例,或者为实例提供单参数数据
var oneArgumentPooler = function (copyFieldsFrom) {
  var Klass = this;
  if (Klass.instancePool.length) {
    var instance = Klass.instancePool.pop();
    Klass.call(instance, copyFieldsFrom);
    return instance;
  } else {
    return new Klass(copyFieldsFrom);
  }
};

var twoArgumentPooler = function (a1, a2) {
  var Klass = this;
  if (Klass.instancePool.length) {
    var instance = Klass.instancePool.pop();
    Klass.call(instance, a1, a2);
    return instance;
  } else {
    return new Klass(a1, a2);
  }
};

var threeArgumentPooler = function (a1, a2, a3) {
  var Klass = this;
  if (Klass.instancePool.length) {
    var instance = Klass.instancePool.pop();
    Klass.call(instance, a1, a2, a3);
    return instance;
  } else {
    return new Klass(a1, a2, a3);
  }
};

var fourArgumentPooler = function (a1, a2, a3, a4) {
  var Klass = this;
  if (Klass.instancePool.length) {
    var instance = Klass.instancePool.pop();
    Klass.call(instance, a1, a2, a3, a4);
    return instance;
  } else {
    return new Klass(a1, a2, a3, a4);
  }
};

// 销毁实例数据,并将实例推入实例池Klass.instancePool中
var standardReleaser = function (instance) {
  var Klass = this;
  !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? 
    invariant(false, 'Trying to release an instance into a pool of a different type.') 
    : _prodInvariant('25') : void 0;
  instance.destructor();
  if (Klass.instancePool.length < Klass.poolSize) {
    Klass.instancePool.push(instance);
  }
};

var DEFAULT_POOL_SIZE = 10;
var DEFAULT_POOLER = oneArgumentPooler;

// 将构造函数CopyConstructor工厂化,调用getPooled方法生成实例,release方法销毁实例数据
// release方法销毁实例数据的同时,将实例推入instancePool实例池中,可通过getPooled方法取出
// release方法的执行需要构造函数CopyConstructor内部包含destructor原型方法
// poolSize约定实例存储个数,默认为10
// 当次参pooler存在时,以pooler替代默认创建实例的方法oneArgumentPooler,将单参数传入构造函数
var addPoolingTo = function (CopyConstructor, pooler) {
  var NewKlass = CopyConstructor;
  NewKlass.instancePool = [];
  NewKlass.getPooled = pooler || DEFAULT_POOLER;
  if (!NewKlass.poolSize) {
    NewKlass.poolSize = DEFAULT_POOL_SIZE;
  }
  NewKlass.release = standardReleaser;
  return NewKlass;
};

var PooledClass = {
  addPoolingTo: addPoolingTo,// 将构造函数转化为工厂函数,提供实例池,管理实例数据的销毁和生成
  oneArgumentPooler: oneArgumentPooler,// 单参数创建实例
  twoArgumentPooler: twoArgumentPooler,// 双参数创建实例
  threeArgumentPooler: threeArgumentPooler,
  fourArgumentPooler: fourArgumentPooler
};

module.exports = PooledClass;

相关推荐