After asking it in stackoverflow : polymorphism-and-tree-structre
I came to a conclusion that I am not being specific and my question is not about any specific technology so I will try to rewrite it.
in the stackoverflow question I wrote about a grandparent/parent/child classes
in order for my question to be concise, this time I will be specific:
My real domain is of army simulator/game
the domain models are :
Corps -> Division -> Brigade which form sort of a tree structure
a Brigade parent must be a Division, a Division parent must be a Corps
a unit without a parent (except corps is not allowed)
furthermore the game is divided into players from three roles : corps general, divisional general and brigade general, each player need to select his managed unit according to his role - corps general selects a corps etc..
The ui for managing units looks like a tree in which you add, delete and edit the units:
- coprs
- division
- birgade
- division
In my previous question the answer I got was to model it as
asbtact class Unit {
List<Unit> children;
Unit parent;
}
which means I don't treat each unit type any differently However, it doesn't fit quite well to my game, since it seems awkward to determine the unit type by state(doesn't have parent == corps for example), it allows for situations where a brigades parent is a corps which is not possible. and I don't want a corps general to be able to select a brigade to manage just because somehow it wasn't assigned a parent and thus the game thinks its a corps. to be more presice, I don't want to determine the units type by their location in the three, but rather the opposite, determine their location by their type.
So my question is how do you think is the best way to model it in classes?
I thought of a class of each type
interface Unit {
Unit getParent();
List<Unit> getChildren()
}
class Brigade implements Unit
class Divison implements Unit
class Corps implements Unit