Java: Cellular Automata with Typed Cells

I'm working on a Java honeycomb implementation (not sure if that is technically, given what follows) in which individual cells can be of different types that encapsulate different CA data and rules. There can be a large number of types, and I want to be able to dynamically include new ones without having to maintain other code.

All cell types come from a common base class. Each update () method of a cell is called exactly once per simulation frame:

public abstract class Cell
{
    public abstract void update(Cell[] neighbors);
}

      

This works great when the CA rules only need the data of the corresponding cell, for example:

public class CellTypeA extends Cell
{
    public int Data = 0;

    @Override
    public void update(Cell[] neighbors)
    {
        Data++;
    }
}

      

However, I have some modeling rules that require a cell to query neighboring cells for data, but only if they are of a type that has the specified 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 would rather avoid the smelly instance if possible. I also can't just push getData () into the superclass to achieve polymorphism, as the actual data structure of these cells will be somewhat more complex and varied. I've read about the GoF Visitor pattern to solve instanceof abuse, but I can't figure out how to apply it to this problem. Thoughts on how to do this, or other ways to solve the problem?

Thank! Steve

+3


source to share


1 answer


I played around and couldn't figure out how to make a visitor template a) neatly deal with the two points to visit and b) be pluggable as you need.

This works, but probably hides instanceof

inside the Guava stuff:



import com.google.common.collect.Iterables;
import java.util.Arrays;

public class CellTypeB extends Cell
{
    public boolean State = false;

    @Override
    public void update(Cell[] neighbors) {
        Iterable<CellTypeA> onlyAs = Iterables.filter(Arrays.asList(neighbors), CellTypeA.class);
        for(CellTypeA a: onlyAs) {
            State = (a.getData() > 10);
        }   
    }   
}   

      

PS Did you mean to use |=

when assigning a value in State

a loop?

+2


source







All Articles