我正在使用一个符号类(周期元素),它定义为:
enum Symbol{
n(0),
H(1),
He(2),
Li(3),
Be(4),
B(5),
C(6),
N(7),
O(8),
F(9),
Ne(10),
//...
private final int atomicNumber;
Symbol(int atomicNumber)
{
this.atomicNumber = atomicNumber;
}
public int getAtomicNumber() {return atomicNumber;}
我正在写一个元素类(化学元素):
enum Element {
Neutron(Symbol.n, "Neutron"),
Hydrogen(Symbol.H, "Hydrogen"),
Helium(Symbol.He, "Helium"),
Lithium(Symbol.Li, "Lithium"),
Beryllium(Symbol.Be, "Beryllium"),
Boron(Symbol.B, "Boron"),
Carbon(Symbol.C, "Carbon"),
Nitrogen(Symbol.N, "Nitrogen"),
Oxygen(Symbol.O, "Oxygen"),
Fluorine(Symbol.F, "Fluorine"),
Neon(Symbol.Ne, "Neon"),
//...
private final Symbol symbol;
private final String name;
Element(Symbol symbol, String name)
{
this.symbol = symbol;
this.name = name;
}
public Symbol getSymbol(){return symbol;}
}
我希望我的Element类能够简单地访问atomicNumber
。我试图禁止getter链接:
// Chaining getters
Element.H.getSymbol().getAtomicNumber();
我应该使用以下哪种解决方案?为什么?
解决方案1:
private final Symbol symbol;
private final String name;
private final int atomicNumber; // I added a field to Element
Element(Symbol symbol, String name)
{
this.symbol = symbol;
this.name = name;
this.atomicNumber = symbol.getAtomicNumber();
}
// I implemented the corresponding getter (this.atomicNumber)
public int getAtomicNumber(){return atomicNumber;}
解决方案2:
private final Symbol symbol;
private final String name;
Element(Symbol symbol, String name)
{
this.symbol = symbol;
this.name = name;
}
// I get atomicNumber from this.symbol
public int getAtomicNumber(){return symbol.getAtomicNumber());}
谢谢。
答案 0 :(得分:2)
如果你认为,没有链接吸气剂的便利性很重要,你应该使用第二种方法。重复字段容易出错。 你应该检查你的基本假设 - 我认为原子序数属于元素而不是符号;有一个元素周期表,而不是符号。