在枚举中耦合

时间:2013-12-06 16:13:58

标签: java enums decoupling

我遇到过一些作为枚举编写的状态机的例子。例如:

public enum State {
    INITIAL {
        @Override
        public State process(char ch) { return MIDDLE; }
    },

    MIDDLE {
        @Override
        public State process(char ch) {
            switch (ch) {
                case 'a': return INITIAL;
                default: return FINAL;
            }
        }
    },

    FINAL {
        @Override
        public State process(char ch) { return FINAL; }
    };

    public abstract State process(char ch);

    public static State initial() { return INITIAL; }
}

让我感到担忧的是让常数彼此了解。 它们的实现可能会发生变化,如果添加(或删除)常量,则会隐含更多变化。

但是,除非外部代码直接引用常量并对转换表做出假设,否则所有更改都包含在枚举中。

那么,这段代码是高度耦合的,松散耦合的,还是主观的

1 个答案:

答案 0 :(得分:2)

我认为这对于灵活的工具来说太紧密了。

更宽松的东西会更灵活:

public enum State {
  INITIAL,
  MIDDLE,
  FINAL;
  public static State initial() {
    return INITIAL;
  }

}

// A 'null' for the Character matches anything.
static Map<Pair<State,Character>, State> machine = new HashMap<>();
static {
  // Always transit from INITIAL to MIDDLE
  machine.put(new Pair<State,Character>(State.INITIAL,null), State.MIDDLE);
  // An 'a' transitrs us to FINAL
  machine.put(new Pair<State,Character>(State.MIDDLE,'a'), State.FINAL);
  // Anything else takes us back to INITIAL
  machine.put(new Pair<State,Character>(State.MIDDLE,null), State.FINAL);
  // Stay in FINAL once there.
  machine.put(new Pair<State,Character>(State.FINAL,null), State.FINAL);

}