Structure of system with polymorphism
I have a
Grid
with Cell
s, each Cell
has a CellEntities
list of CellEntity
. Each CellEntity
has a data object called CellEntityData
. Classes that derive from CellEntity
will have different functions, they could have different types of CellEntityData
, but the way I have things set up right now that's not necessary, but might be in the future.
But the important part is to be able to differentiate between different CellEntity
classes because I want Cell
to do different things depending on the CellEntity
(namely Instantiate different GameObjects in unity, among other things)
What is the best way to go about implementing entities with this framework?
Should CellEntity
and CellEntityData
be interfaces? Abstract classes?13 Replies
1. Do you ever expect a
CellEntity
to be instantiated on its own? If not, use an interface or an abstract class.
2. Does the CellEntity
class contain any functionality or data that is shared to its children? If yes, use an abstract class1. no
2. yes
if i use an abstract class, how do i differentiate between the classes that inherit from
CellEntity
in Cell
?You can use pattern matching, for example
that was my first thought but i was thinking there has to be a better way of doing it
Why?
idk people tend to avoid big if else statements
it feels a bit awkward
inelegant maybe is the right word
Could use a switch expression where appropriate
Other than that... not really any other way of calling different code based on the subtype
okay gotcha
tyty i'll look at implementing this now
in
Cell
i have a PopulateCell
function that takes in a list of EntityData
and goes through and instantiates and initialises each Entity
with its EntityData
to load the world from a save
how do i differentiate between different EntityData
?
maybe make it abstract as well and have each Entity
have a different type of data, or maybe through an enum?The same or similar way
Pattern matching, an enum discriminator also works, sure
ok tyty
nice pfp btw s2 when
Still waiting lol
perhaps you want to use the visitor pattern https://refactoring.guru/design-patterns/visitor
Visitor
Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate.
oh interesting i'll check it out ty