首页 > 技术文章 > OO_JAVA_JML系列第三次作业__架构之谈

-atom 原文

OO_JAVA_JML系列第三次作业


																						## ————架构之谈

出发点

操作的可分离性

总的来说,我们的计算最短路,计算最少换乘,都可以视作计算一条路径的权值之和,然后找到权值之和最小的那一条路径,返回对应的权值。

所以我的出发点就是:分离出如下两个操作

  1. 遍历图结构生成两点间路径
  2. 根据拿到的路径计算权值之和

通过分离上述两个函数,可以大大降低我的单个方法的复杂度,起码,将其分成了两个层次的功能区分的函数,具体实现可以加入更多的层级,分离处理的逻辑。

操作本身的多样性

我们的权值之和的计算,有4种方式:

  1. 计算最短路径
  2. 计算最少换乘
  3. 计算最小票价
  4. 计算最小不满意度

所以,我想到了表驱动编程,就是按照switch的逻辑,指派属性对应的操作函数,通过map哈希表的形式实现,这也是我的架构的一个核心所在,通过此种方法降低一些复杂度。

实现手段:表驱动编程

储存

T是继承自Enum类型的类型,就是枚举类型。

Operation是一个接口,功能是对给定路径计算对应的权值之和。

public class GraphStructure<T extends Enum> {
    ...

	private HashMap<T, HashMap<SymPair<Node>, Integer>> shortestLength;
    private HashMap<T, Operation> operations; 

	public void setOperation(T type, Operation operation) {
        this.shortestLength.put(type, new HashMap<>());
        this.operations.put(type, operation);
    }
    
    ...


    private void addShortestLengthPair(T type, Node from, Node to) {
        List<List<Node>> lists = TraverseFunc.depthFirstTraversing(from, to, table);
        Map<SymPair<Node>, Integer> map = shortestLength.get(type);
        Operation operation = operations.get(type);
        TraverseFunc.addShortestLength(from, to, lists, edgeColors, map, operation);
    }
}

注册

CalculateMethod是上述的泛型,用于表示操作的属性;每个操作都有对应的实现了Operation接口的类;

通过传递键:枚举类型;值:实现Operation接口的类,来完成注册操作方法的过程。

public class MetroSystem extends MyPathContainer implements RailwaySystem {
    private GraphStructure<CalculateMethod> graph;

    public MetroSystem() {
        super();
        this.graph = new GraphStructure<>();
        this.graph.setOperation(CalculateMethod.shortestRouteLength,
                                new CalculateRouteLength());
        this.graph.setOperation(CalculateMethod.leastTicketPrice,
                                new CalculateTicketPrice());
        this.graph.setOperation(CalculateMethod.leastTransferLength,
                                new CalculateTransferLength());
        this.graph.setOperation(CalculateMethod.leastUnpleasementCount,
                                new CalculateUnpleasantCount());
    }
 
    ...
    
}

推荐阅读