2013-03-23 36 views
0

我有一个命令列表,我按照定义的顺序运行。使用Java ENUM作为命令列表的缺陷

public enum TextFormatter { 
Bold("bold",new BoldCommand()), 
Superfancy("superfancy",new SuperfancyCommand()); 

    String tag; 
    Command cmd; 
    FormatterCommand(String tag, Command cmd) { 
     this.tag = tag; 
     this.cmd = cmd; 
    } 
    public void format(InputStream in, OutputStream out) { 
     cmd.format(in,out); 
    } 
    public String toString() { 
     return tag; 
    } 
} 

在大多数情况下,我会这样运行了他们:

for(TextFormatter formatter : TextFormatter.values()) { 
    formatter.format(in,out); 
} 

但有时JSON会带有特殊格式的,那么我会用TextFormatter.tag使名单,并运行在不同的顺序指令。感谢ENUM,我的可用命令字典集中在一个地方。

  1. 这种设计的缺点是什么?
  2. 如果它运行速度超快? [因为我用枚举而不是列表]
+2

这甚至没有编译 - 你的构造函数被命名为'FormatterCommand',但你的类被命名为'TextFormatter' – Bohemian 2013-03-23 11:43:23

+0

如果你喜欢它,使用它。 – flup 2013-03-23 12:02:27

+0

枚举总是大写! – 2013-03-23 12:23:26

回答

0

这个设计的缺点是什么?

您没有向我们展示足够的设计来做出判断。

你没有考虑过的一件事是你如何将字符串映射到这些对象。

如果它运行速度超快? [因为我使用枚举而不是列表]

最有可能的是,性能差异太小,无法衡量。


底线:如果您认为此方法使您的代码更易于理解,请使用它。