您将如何在 Java 中创建一个音符枚举,每个音符都有一个 Octave 音阶,然后是一个键控变量?这是我目前所拥有的...
public enum Notes
{
c,
cS,
d,
dS,
e,
f,
fS,
g,
gS,
a,
aS,
b;
int octave;
boolean isPlaying;
}
所以当我在我的代码中访问枚举时,我会写这样的东西......
Notes.c.octave = 4;
Notes.c.isPlaying = true;
现在这是我的问题:如何为每个 Octave 音阶中的每个音符设置一个 isPlaying boolean 值?
像这样:
Notes.c.octave.isPlaying = true;
或者我必须这样走:
public enum Notes
{
c1,
cS1,
d1,
dS1,
e1,
f1,
fS1,
g1,
gS1,
a1,
aS1,
b1
c2,
cS2,
d2,
dS2,
e2,
f2,
fS2,
g2,
gS2,
a2,
aS2,
b2;
etc...
boolean isPlaying;
}
预先感谢您花时间回答这个问题!
最佳答案
您不应该修改枚举的字段!!!
原因是每个实例在 JVM 中都是唯一的(就像一个单例),使用同一个音符的另一个线程将共享同一个 playing
字段,这是一个严重错误的设计。
此外,您的枚举应该命名为单数 Note
,而不是复数 Notes
。原因应该很明显:枚举的每个实例代表一个音符,而不是多个音符。
正确的做法是创建一个包含 3 个字段的类:
public class Tone {
private Note note;
private int octave;
private boolean playing;
// with getters and setters
}
因为每个音符都可以是降♭、升♯、双降𝄫和双升𝄪,所以我会使用这个更准确地反射(reflect)现实的模型。此外,即使是 playing
字段也感觉不对。感觉更像是Tone
应该是immutable和一些其他实体(例如 Player
)知道当前正在播放什么 Tones
,所以我建议这样做:
public enum Note {
C, D, E, F, G, A, B
}
public enum Shift {
DoubleFlat, Flat, Natural, Sharp, DoubleSharp
}
public class Tone {
private Note note;
private Shift shift;
private int octave;
private int duration; // include a duration - perhaps milliseconds
// with only getters, being immutable
}
public class Player {
// has references to `Tones` and a way to schedule their being played
}
关于Java 枚举音符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13205926/