如何使用多个列表重构 class + 每个列表的 getter 和 setter

How to refactor a class with multiple Lists + getters and setters for each list

我有以下 class:

public class RefactorMe {

  private static List<Event<Apple>> mAppleEventList = new ArrayList<Event<Apple>>();
  private static List<Event<Banana>> mBananaEventList = new ArrayList<Event<Banana>>();
  private static List<Event<Orange>> mOrangeEventList = new ArrayList<Event<Orange>>();

  public static List<Event<Apple>> getAppleList() {
    return mAppleEventList;
  }

  public static List<Event<Banana>> getBananaEventList() {
    return mBananaEventList;
  }

  public static List<Event<Orange> getOrangeList() {
    return mOrangeEventList;
  }

  public static void addAppleEvent(Event<Apple> pEvent) {
    mAppleEventList.add(pEvent);
  }

  public static void addBananaEvent(Event<Banana> pEvent) {
    mBananaEventList.add(pEvent);
  }

  public static void addOrangeEvent(Event<Orange> pEvent) {
    mOrangeEventList.add(pEvent);
  }

}

我尝试使用访问者模式重构它,但由于泛型而无法使其工作。有更好的方法吗?

通过使用此处的地图关注@user902383 是 Java 7 中适合您的解决方案:

public class RefactorMe {
  class Event<K> {
    public K getNewObject() {
      return null;
    }
  }

  private static Map<Class<?>, List<Event<?>>> eventLists = new HashMap<>();

  public static <E> List<Event<E>> getEventList(Class<E> clazz) {
    return (List) eventLists.get(clazz);
  }

  public static <E extends Event<E>> void addEvent(Event<E> pEvent) {
    Class<E> key = (Class<E>) pEvent.getNewObject().getClass();
    List<Event<?>> events = eventLists.get(key);
    if (events == null) {
      events = new ArrayList<>();
      eventLists.put(key, events);
    }
    events.add(pEvent);
  }
}