繁体   English   中英

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

[英]What is a good way to implement calculations for extended classes?

我有以下课程:

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;
    }

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

我认为对此有一个正确的答案,只需在Map上有一个抽象的getMoveCost方法并在每个子类中实现它。 然后你可以打电话给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();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM