Java Enums: Two enum types, each containing references to each other?

爷,独闯天下 提交于 2019-11-27 01:33:14
falsarella

One of the best ways would be using the enum polymorphism technique:

public class EnumTest {
    public enum Foo {
        A {

            @Override
            public Bar getBar() {
                return Bar.Alpha;
            }
        },
        B {

            @Override
            public Bar getBar() {
                return Bar.Delta;
            }
        },
        C {

            @Override
            public Bar getBar() {
                return Bar.Alpha;
            }
        },

        ;

        public abstract Bar getBar();
    }

    public enum Bar {
        Alpha {

            @Override
            public Foo getFoo() {
                return Foo.A;
            }
        },
        Beta {

            @Override
            public Foo getFoo() {
                return Foo.C;
            }
        },
        Delta {

            @Override
            public Foo getFoo() {
                return Foo.C;
            }
        },

        ;

        public abstract Foo getFoo();
    }

    public static void main(String[] args) {
        for (Foo f : Foo.values()) {
            System.out.println(f + " bar " + f.getBar());
        }
        for (Bar b : Bar.values()) {
            System.out.println(b + " foo " + b.getFoo());
        }
    }
}

The above code produces the output you want:

A bar Alpha
B bar Delta
C bar Alpha
Alpha foo A
Beta foo C
Delta foo C

See also:

weiji

The issue isn't so much "two enums reference each other", it's more "two enums reference each other in their constructors". This circular reference is the tricky part.

How about using Foo.setResponse(Bar b) and Bar.setResponse(Foo f) methods? Instead of setting a Foo's Bar in the Foo constructor (and similarly a Bar's Foo in the Bar constructor), you do the initialization using a method? E.g.:

Foo:

public enum Foo {
  A, B, C;

  private void setResponse(Bar b) {
    this.b = b;
  }

  private Bar b;

  public Bar getB() {
    return b;
  }

  static {
    A.setResponse(Bar.Alpha);
    B.setResponse(Bar.Delta);
    C.setResponse(Bar.Alpha);
  }
}

Bar:

public enum Bar {
  Alpha, Beta, Delta;

  private void setResponse(Foo f) {
    this.f = f;
  }

  private Foo f;

  public Foo getF() {
    return f;
  }

  static {
    Alpha.setResponse(Foo.A);
    Beta.setResponse(Foo.C);
    Delta.setResponse(Foo.C);
  }
}

Also, you mention that Foo and Bar are two types of messages. Would it be possible to combine them into a single type? From what I can see, their behavior here is the same. This doesn't fix the circular logic, but it might give you some other insight into your design...

Since it seems you're going to be hard-coding anyways, why not have something like

public static Bar responseBar(Foo f) {
 switch(f) {
  case A: return Bar.Alpha;
  // ... etc
 }
}

for each enum? It looks like you have some overlapping responses in your example, so you could even take advantage of cases falling through.

EDIT:

I like Tom's suggestion of the EnumMap; I think performance is probably faster on the EnumMap, but the sort of elegant construction described in Effective Java doesn't seem to be afforded by this particular problem - however, the switch solution offered above would be a good way to construct two static EnumMaps, then the response could be something like:

 public static Bar response(Foo f) { return FooToBar.get(f); }
 public static Foo response(Bar b) { return BarToFoo.get(b); }

Interesting design. I see your need, but what are you going to do when the requirements shift slightly, so that in response to Foo.Epsilon, app_1 should send either a Bar.Gamma or a Bar.Whatsit?

The solution you considered and discarded as hackish (putting the relation into a map) seems to give you much more flexibility, and avoids your circular reference. It also keeps the responsibility partitioned: the message types themselves shouldn't be responsible for knowing their response, should they?

You can use EnumMap, and fill it within one of the enums.

private static EnumMap<Foo, LinkedList<Bar>> enumAMap;

public static void main(String[] args) throws Exception {
    enumAMap = new EnumMap<Foo, LinkedList<Bar>>(Foo.class);
    System.out.println(Bar.values().length); // initialize enums, prevents NPE
    for (Foo a : Foo.values()) {
        for (Bar b : enumAMap.get(a)) {
            System.out.println(a + " -> " + b);
        }
    }
}

public enum Foo {
    Foo1(1),
    Foo2(2);

    private int num;

    private Foo(int num) {
        this.num = num;
    }

    public int getNum() {
        return num;
    }
}

public enum Bar {
    Bar1(1, Foo.Foo1),
    Bar2(2, Foo.Foo1),
    Bar3(3, Foo.Foo2),
    Bar4(4, Foo.Foo2);

    private int num;
    private Foo foo;

    private Bar(int num, Foo foo) {
        this.num = num;
        this.foo = foo;
        if (!enumAMap.containsKey(foo)) {
            enumAMap.put(foo, new LinkedList<Bar>());
        }
        enumAMap.get(foo).addLast(this);
    }

    public int getNum() {
        return num;
    }

    public Foo getFoo() {
        return foo;
    }
}

Output:

4
Foo1 -> Bar1
Foo1 -> Bar2
Foo2 -> Bar3
Foo2 -> Bar4
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!