我已经在 C#(或 Java,无关紧要)中实现了一个简单的树结构,其中一切都围绕抽象类 Node 及其一些子类展开。 Node 提供与数学图论相关的方法和属性。例如 Node.Parent 引用父节点,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 类的“图论方法”在给定的树上实现他自己的计算。
您知道什么是好的设计模式吗?
最佳答案
这尖叫着 Visitor模式。
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
类。您只需创建一个新的访客实现。
class WeightVisitor implements Visitor{
int weight = 0;
void visit(Node n){
weight += ...
}
}
然后每次你想计算重量
WeightVisitor visitor = new WeightVisitor();
rootNode.accept(visitor);
int weight = visitor.getWeight();
关于java - 面向对象设计模式 : How to add methods dynamically?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27158546/