我正在使用通過HTTP POST使用雅馬哈藍光播放器的API的Android應用程序(Java)。該播放器具有嚴格的XML格式命令集。命令遵循層次結構:雖然大多數外部XML元素總是相同的,但內部結構屬於播放器函數的類型。例如,play/pause/stop函數在XML中具有相同的路徑,而skip函數具有其他父元素。你可以在下面的代碼示例中看到我的意思。在Java中定義嵌套類/對象/枚舉結構的最佳方式是什麼?
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>";
}
}
正如你所看到的,我嘗試了平坦的枚舉方式,它工作正常。我可以用枚舉與我REMOTECONTROL類就像這樣:
remoteControl.execute(BD_A1010.PLAY);
枚舉的.toXml()方法返回發送到玩家需要完整的XML代碼。下面是我的問題:我需要一個更好的方法來構建Java類中的函數層次結構。我想這樣使用它:
remoteControl.execute(BD_A1010.Main_Zone.Power_Control.Power.On);
像嵌套的枚舉或類。命令的每個級別都應該在其內部定義其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>
如你所描述的那樣做的問題是什麼,我的意思是將枚舉嵌套到另一個枚舉? – maks
另外,YmanaCommand接口是否定義了toXml方法? – maks
據我所知,嵌套的枚舉在Java中是不可能的,是嗎? –