我试图在Google和StackOverflow上搜索实例缓存和单例,但没有成功,只看到有关module.exports的帖子,如果您知道回答此问题的帖子,请随时引用它。谢谢!
我有一个应用程序需要处理一组很少更改的对象,因此需要进行缓存以进行性能优化。
这是一个玩具示例,其中直接设置了一个属性。
当我调用应用程序时,我导出一个对象,该对象将包含assets_cached.js中的一组缓存对象:
const Assets = {};
module.exports.Assets = Assets;
在应用程序的另一个模块中,我有一个ES6类:
const _ = require('lodash')
const { Assets } = require('./assets_cached')
class Asset {
constructor(id, some_property) {
if (id in Assets) {
// Update instance data with cached properties
_.assign(this, Assets_cached[id]);
} else {
// If it's not cached, create a new object
this.id = id;
this.some_property = some_property;
// Cache this object
Assets_cached[id] = this;
}
}
getProperty() {
return this.some_property;
}
setProperty(value) {
this.some_property = value;
// Is there a way of avoiding having to do this double assignment?
Assets_cached[id].some_property = value;
}
}
module.exports = Asset;
我怎样才能避免必须设置some_property两次(在当前实例和缓存中,同时确保其他实例并行更新)?
理想情况下,我想做类似的事情:
if (id in Assets) {
this = Assets.cached[id]
}
在构造函数中,但这是不可能的。
最优雅和正确的方法是什么?
答案 0 :(得分:2)
理想情况下,我想在构造函数
中执行--file
之类的操作
这里的magic关键字是this = Assets.cached[id]
。您可以return an arbitrary object from the constructor使用它而不是return
。
this
答案 1 :(得分:1)
以下是the comment that was made some half an hour ago ...
的方法const { Assets_cached } = require('./assets_cached');
// const { AssetStore } = require('./assetstore');
class Asset {
constructor(id, some_property) { // clean/lean constructor.
this.id = id;
this.some_property = some_property;
}
getProperty() {
return this.some_property;
}
setProperty(value) {
this.some_property = value;
}
}
function isAsset(type) {
// poor man's approach ... change to something more feasible.
return (type instanceof Asset);
}
function createAsset(id, some_property) { // factory that also handles caching.
var
asset = Assets_cached[id];
// asset = AssetStore.get(id);
if (!(asset && isAsset(asset))) {
asset = Assets_cached[id] = (new Asset(id, some_property));
// AssetStore.put(id, (asset = new Asset(id, some_property)));
}
return asset;
}
module.exports = {
create : createAsset,
isAsset : isAsset
};
<强> 注意 强>
还应该考虑为Assets_cached
提供最小的API,例如put
/ set
,get
和delete
,而不是Assets_cached
是一个完全暴露的,普通的键值商店。