我正在为应用程序制作视频设置屏幕,我需要一种在将每个设置发送到将创建HTML元素的UI管理器之前存储每个设置的方法。我以前将它们存储为如下数组:
let options = [
new BoolOption("Ragdolls", 1, "description here"),
new QualityOption("SkeletalMeshLODBias", 0, "description here"),
new ResolutionOption("Character Texture Resolution", 4, "description here"),
new Option("Video Memory Texture Pool", [150, 300, 600], 0, "description here")
]
这种方法的缺点是,由于存储了很多类型并且它们的参数不匹配,因此可读性受到了损害-特别是在处理大量值时。考虑到这一点,我将其设为对象/字典,并编写了将其转换回数组的函数:
let optionsDictionary = {
ragdolls: {
name: "Ragdolls",
type: BoolOption,
defaultIndex: 1,
description: "description here"
},
skeletalMeshLODBias: {
name: "SkeletalMeshLODBias",
type: QualityOption,
defaultIndex: 0,
description: "description here"
},
characterTextureRes: {
name: "Character Texture Resolution",
type: ResolutionOption,
defaultIndex: 4
},
texturePool: {
name: "Video Memory Texture Pool",
type: Option,
states: [150, 300, 600],
defaultIndex: 0,
description: "description here"
},
}
let optionsDictionaryToOptionsArray = (optionsDictionary) => {
let options = []
for (let key in optionsDictionary) {
let option
if (optionsDictionary.hasOwnProperty(key)) {
let setting = optionsDictionary[key],
name = setting.name,
type = setting.type,
defaultIndex = setting.defaultIndex,
description = setting.description || ""
switch (type) {
case Option:
let states = setting.states
option = new Option(name, states, defaultIndex, description)
break
case BoolOption:
option = new BoolOption(name, defaultIndex, description)
break
case RangeOption:
let min = setting.min,
max = setting.max
option = new RangeOption(name, min, max, defaultIndex, description)
break
case QualityOption:
option = new QualityOption(name, defaultIndex, description)
break
case ResolutionOption:
option = new ResolutionOption(name, defaultIndex, description)
break
default:
throw new Error()
}
}
options.push(option)
}
return options
}
但是我仍然觉得它可以进一步改进或使用更优雅的解决方案来制作,因为每个字典对象属性中的键随其.type
而变化。也许我用第二种方法使情况变得更糟。有什么建议吗?
答案 0 :(得分:0)
我相信,您的问题可能会存在偏见,因为人们可能会在看起来“最有趣”的问题上意见分歧。因此,我将在这里提到另一个可用的格式设置选项:构造函数通过单个对象接受参数:
let options = [
new BoolOption({
name: 'Ragdolls',
defaultIndex: 1,
description: 'description here'
}),
new QualityOption({
name: 'SkeletalMeshLODBias',
defaultIndex: 0,
description: 'description here'
}),
// ...
// ...
// ...
];
切换到这种格式几乎不需要重构-对于像这样的构造函数:
let BoolOption = function(name, defaultIndex, description) {
// ...
};
只需将{
和}
放在参数周围,并且所有参数都应相同:
let BoolOption = function({ name, defaultIndex, description }) {
// ...
};