什么是实现扩展类计算的好方法?

quhf5bfb  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(315)

我有以下课程:

public class Node {
    private int x;
    private int y;

}
public abstract class Map {
    protected Node[][] grid;

    public abstract Set<Node> findNeighbours(Node node);
}
public class SquareMap extends Map {
    private static final int VERTICAL_COST= 10;
    private static final int HORIZONTAL_COST= 10;
    private static final int DIAGONAL_COST = 14;

    @Override
    public Set<Node> findNeighbours(Node node) {
        //return the 8 adjacent nodes
    }
}
public class HexMap extends Map {
    private static final int MOVE_COST = 10;

    @Override
    public Set<Node> findNeighbours(Node node) {
        //return the 6 adjacent nodes
    }
}

我想创建一个方法

public int calculateMoveCost(Node current, Node target, <whatever else is needed>) {}

其中我只传递节点,方法中的逻辑,或者节点,或者Map识别出我使用的是什么类型的Map。我当前的解决方案如下所示:

private int calculateMoveCost(Node current, Node target, Map map) {
        int cost;
        if(isHexMap(map)) {
            cost = map.getMoveCost();
        } else {
            if(isSquareMap(map)) {
                if(verticalNeighbours(current, target)) {
                    cost = map.getVerticalMoveCost();
                } else {
                    cost = map.getHorizontalMoveCost();
                }
            }
        }
        return cost;
    }

当我看到这段代码时,我认为必须有更好的方法来实现它。你能推荐一个很好的面向对象的实现方法吗?我可以在任何对象中创建任何引用,目标是有一个好的解决方案。谢谢!

ndasle7k

ndasle7k1#

我确实认为有一个正确的答案,只是有一个摘要 getMoveCost 上的方法 Map 并在每个子类中实现它。那你就直接打电话吧 map.getMoveCost(from, to) .

public abstract class Map {
    protected Node[][] grid;

    public abstract int getMoveCost(Node current, Node target);
    public abstract Set<Node> findNeighbours(Node node);
}

public class SquareMap extends Map {
    private static final int VERTICAL_COST= 10;
    private static final int HORIZONTAL_COST= 10;
    private static final int DIAGONAL_COST = 14;

    @Override
    public Set<Node> findNeighbours(Node node) {
        //return the 8 adjacent nodes
    }

    @Override
    public int getMoveCost(Node current, Node target) {
        if(verticalNeighbours(current, target)) {            
            cost = getVerticalMoveCost();
        } else {
            cost = getHorizontalMoveCost();
        }
    }
}

相关问题