我用C#(或Java,没什么大不了)实现了一个简单的树结构,其中所有内容都围绕抽象类Node及其一些子类展开。Node提供与数学图论相关的方法和属性。例如,Node.Parent引用父Node,而Node.Children引用子节点
class Node {
Node Parent;
Node[] Children;
void appendNode(Node node) { ... }
}
我正在使用树执行计算。计算涉及很多递归,我还需要为每个节点存储中间值。对于每次计算,我都向Node类引入了其他属性和方法,例如
class Node {
Node Parent;
Node[] Children;
// Calculate weight
int weight; // current weight
void recalculateWeight() {
// perform some heavily recursive stuff
// involving Parent.recalculateWeight()
// and update the value of the variable weight
}
int price; // current price
void recalculatePrice() {
// perform some heavily recursive stuff
// involving Parent.recalculatePrice()
// and update the value of the variable price
}
void appendNode(Node node) {
// ...
recalculateWeight();
recalculatePrice();
}
}
但是现在我不得不放弃这种方法,因为应该动态添加计算值,而无需更改Node类。动态意味着其他人应该能够仅依靠Node类的“图形理论方法”在给定的树上实现自己的计算。
您有什么主意吗?
这尖叫着访客模式。
interface Visitor{
visit(Node node);
}
class Node{
//...
void accept(Visitor v){
//feel free to change visit order to viist children first
v.visit(this);
for(Node child : children){
v.visit(child);
}
}
}
然后,您可以使所有不同的计算成为不同的访问者。创建新的计算或遍历类型根本不会更改Node
类。您只需创建一个新的Visitor实现。
class WeightVisitor implements Visitor{
int weight = 0;
void visit(Node n){
weight += ...
}
}
然后每次您要计算体重
WeightVisitor visitor = new WeightVisitor();
rootNode.accept(visitor);
int weight = visitor.getWeight();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句