[英]Proper Large Enum Design
我最近完成了计算机图形学课程的分子/蛋白质查看器的工作。 原子显然是此类程序中非常重要的部分。 目前,我有一个包含每个元素(氢,氦等)的大枚举。 每个元素都有相关的信息,例如颜色,半径等。我正在使用扩展类,因此我可以这样写:
float r = Element.Neon.Radius();
我还需要能够从其符号中获取相应的枚举。 我将该方法卡在扩展类中,这有点混乱:
Element carbon = ElementExtensions.FromAbbreviation("C");
我想将更多的数据与特定的Element条目相关联,但是我不确定这是否是一个好的设计。 当前,每组关联数据都需要词典来获取关联数据。 也许我可以使用Dictionar?
如果我使用Element类,则需要确保只有一个氢实例,一个氦实例,等等。我喜欢System.Drawing.Color的设计方式,但我不认为这正是我所需要的(例如,您无需查找ForestGreen的关联数据)。
支持大量但定义明确且数量有限的特定实例的最佳方法是什么?
如果您有很多枚举,则应重新考虑是否应该使用继承。
为何不让Neon从Element继承Element.Neon呢?
class Element
int Radius();
Color Color();
string Symbol();
class Neon : Element
int Radius (return x);
int Color (return Color.Red);
int Symbol (return "NE");
如果只需要一个元素,请考虑使用Singleton。
枚举似乎不是解决此问题的非常合适的方法。 相反,您应该创建一个Element
类,其中包含与每个元素相关的所有信息,以及每个已知元素的静态只读属性:
public class Element
{
private readonly string _symbol;
private readonly int _atomicNumber;
private readonly Color _color
// Private constructor, since you don't want people to be able to "invent" random elements...
private Element(string symbol, int atomicNumber, Color color)
{
_symbol = symbol;
_atomicNumber = atomicNumber;
_color = color;
}
public string Symbol { get { return _symbol; } }
public int AtomicNumber { get { return _atomicNumber; } }
public Color color { get { return _color; } }
// Known elements
private static readonly Element _hydrogen = new Element("H", 1, Color.White);
private static readonly Element _carbon = new Element("C", 6, Color.Black);
private static readonly Element _oxygen = new Element("O", 8, Color.Red);
public static Element Hydrogen { get { return _hydrogen; } }
public static Element Carbon { get { return _carbon; } }
public static Element Oxygen { get { return _oxygen; } }
...
}
这样,有关元素的所有信息都可以放在一个地方,而不是分散在许多不同的地方
将您的元素定义为类,但使用Flyweight模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.