Ber*_*ler 6 java enums nested class
我正在开发一个Android应用程序(Java),它通过HTTP POST使用Yamaha蓝光播放器的API.播放器具有XML格式的严格命令集.命令遵循层次结构:虽然大多数外部XML元素始终相同,但内部结构属于播放器函数的类型.例如,播放/暂停/停止功能在XML中具有相同的路径,而跳过功能具有其他父元素.您可以在下面的代码示例中看到我的意思.
public enum BD_A1010 implements YamahaCommand
{
POWER_ON ("<Main_Zone><Power_Control><Power>On</Power></Power_Control></Main_Zone>"),
POWER_OFF ("<Main_Zone><Power_Control><Power>Network Standby</Power></Power_Control></Main_Zone>"),
TRAY_OPEN ("<Main_Zone><Tray_Control><Tray>Open</Tray></Tray_Control></Main_Zone>"),
TRAY_CLOSE ("<Main_Zone><Tray_Control><Tray>Close</Tray></Tray_Control></Main_Zone>"),
PLAY ("<Main_Zone><Play_Control><Play>Play</Play></Play_Control></Main_Zone>"),
PAUSE ("<Main_Zone><Play_Control><Play>Pause</Play></Play_Control></Main_Zone>"),
STOP ("<Main_Zone><Play_Control><Play>Stop</Play></Play_Control></Main_Zone>"),
SKIP_REVERSE ("<Main_Zone><Play_Control><Skip>Rev</Skip></Play_Control></Main_Zone>"),
SKIP_FORWARD ("<Main_Zone><Play_Control><Skip>Fwd</Skip></Play_Control></Main_Zone>");
private String command;
private BD_A1010 (String command)
{
this.command = command;
}
public String toXml ()
{
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><YAMAHA_AV cmd=\"PUT\">" + this.command + "</YAMAHA_AV>";
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我尝试了扁平的枚举方式,它工作得很好.我可以像我一样使用我的RemoteControl类的枚举:
remoteControl.execute(BD_A1010.PLAY);
Run Code Online (Sandbox Code Playgroud)
枚举的.toXml()方法返回发送给播放器所需的完整XML代码.现在这是我的问题:我需要一种更好的方法来构建Java类中的函数层次结构.我想这样使用它:
remoteControl.execute(BD_A1010.Main_Zone.Power_Control.Power.On);
Run Code Online (Sandbox Code Playgroud)
就像嵌套的枚举或类一样.命令的每个级别都应该在其自身内部定义XML元素.此外,路径上的每个命令只能定义可能的子命令:例如,在Main_Zone.Play_Control之后,我可能只使用.Play或.Skip,而不是.Tray或其他任何东西.在链的末尾,我喜欢调用.toXml()来获取完整的XML命令.
在Java中将这个hiarachy定义为(嵌套)类的最佳方法是什么?应该很容易定义 - 尽可能少的代码.
稍后,应该可以合并两个或多个命令以获得如下所示的组合XML - 但这对于第一次尝试来说并不那么重要.
remoteControl.execute(
BD_A1010.Main_Zone.Power_Control.Power.On,
BD_A1010.Main_Zone.Play_Control.Skip.Rev,
BD_A1010.Main_Zone.Play_Control.Play.Pause
);
<Main_Zone>
<Power_Control>
<Power>On</Power>
</Power_Control>
<Play_Control>
<Skip>Rev</Skip>
<Play>Pause</Play>
</Play_Control>
</Main_Zone>
Run Code Online (Sandbox Code Playgroud)
小智 6
为什么它必须枚举?生成器模式的救援.考虑一下这种味道:http://www.drdobbs.com/jvm/creating-and-destroying-java-objects-par/208403883? pgno = 2而不是香草.核心改进是非常易读的语法:
builder.withProperty(...).withFeature(...).finallyWith(...)
Run Code Online (Sandbox Code Playgroud)