dimanche 13 septembre 2015

How to use generics with multiple coupled objects?

So I'm having trouble wrapping my head around the proper design for this.

My application has two key objects that control state, that need to interact with one another: ItemList, ItemState. These each rely on a generic ITEM_TYPE so they can function in different contexts. They are also abstract to allow for ITEM_TYPE-dependent behavior.

Both pieces need to know the generic type, but moreover, since they talk to one another, they need to know the generic types of one another. (An ItemList< String > instance needs to know that its ItemState field is an ItemState< String > and vice versa).

My current solution works, but it seems awful. There has to be a better way. This is what I'm doing now:

public abstract class ItemState<
  ITEM_TYPE,
  STATE_TYPE extends ItemState<ITEM_TYPE, STATE_TYPE, LIST_TYPE>,
  LIST_TYPE extends ItemList<ITEM_TYPE, STATE_TYPE, LIST_TYPE>> {

}
public abstract class ItemList<
  ITEM_TYPE,
  STATE_TYPE extends ItemState<ITEM_TYPE, STATE_TYPE, LIST_TYPE>,
  LIST_TYPE extends ItemList<ITEM_TYPE, STATE_TYPE, LIST_TYPE>> {

}

Then an implementing class might look like:

class StringState extends ItemState<String, StringState, StringList> {

}
class StringList extends ItemList<String, StringState, StringList> {

}

Note that for ItemState, STATE_TYPE is a reference back to the implementing class, and likewise for ItemList/LIST_TYPE.

Really my problem would be solved if I just make ItemState an inner class of ItemList since there would be an implicit binding and they could share generic declarations, but both classes are so large and standalone, that I would prefer not to do this.

Any suggestions?

Aucun commentaire:

Enregistrer un commentaire