I'm working on a Java-based cellular automata-like implementation (not sure it technically is, given what follows) in which the individual cells may have different types that encapsulate different data and CA rules. There may be a large number of types, and I want to be able to dynamically plug in new ones without having to maintain other code.
All cell types derive from a common base class. Each cell's update() method is called exactly once per frame of the simulation:
public abstract class Cell
{
public abstract void update(Cell[] neighbors);
}
This works fine when the CA rules only need the data of the cell in question, e.g.:
public class CellTypeA extends Cell
{
public int Data = 0;
@Override
public void update(Cell[] neighbors)
{
Data++;
}
}
However, I have some simulation rules that require the cell to query adjacent neighbor cells for data, but only if they are of a type that has said data. There is a strong temptation to use the instanceof operator to accomplish this:
public class CellTypeB extends Cell
{
public boolean State = false;
private void update(Cell[] neighbors)
{
for (Cell c : neighbors)
{
if (c instanceof CellTypeA)
{
State = (((CellTypeA)c).getData() > 10);
}
}
}
}
I'd prefer to avoid the smelly instanceof if possible. I also can't just promote getData() to the superclass to achieve polymorphism, as the actual data structure of these cells will be somewhat more complex and varied. I've been reading about the GoF Visitor pattern to solve instanceof abuse, but I can't seem to figure out how to apply it to this problem. Thoughts on how to do this, or on other ways to approach the problem?
Thanks! Steve