gpt4 book ai didi

java - 容器和元素之间触发事件的解决方案?

转载 作者:行者123 更新时间:2023-11-30 02:41:05 25 4
gpt4 key购买 nike

我有一堂这样的课:

public class Graph {
Map<NodeKey,Node> nodes;

List<RelationKey,Relation> relations;

public void addNode(Node node){
nodes.put(node.key,node);
}

public void addRelation(Relation relationship){
relations.add(relation.key,relation);
}

//getter and setter
}
public class Node {
Map<RelationKey,Relation> relations;

public void addRelationship(Relation relation){
relations.put(relation.key,relation);
}
//getter and setter
}

当调用node.addRelationship(Relationlation)时,Graph如何调用它的方法:addRelation(Relationrelation)。我可以在 Node 类中添加 Graph 属性,但它似乎与 OOP 中的 HAS-A 关系不太接近

最佳答案

您可以像这样使用观察者模式:

class Node extends Observable {

public Node(Observer observer){
addObserver(observer);
}

public void addRelationship(Relation relation){
relations.put(relation.key,relation);
setChanged();
notifyObservers(relation);
}
}


class Graph implements Observer {
@Override
public void update(Observable o, Object arg) {
Relation relation = (Observable)arg;
relations.add(relation.key,relation);
}
}

关于java - 容器和元素之间触发事件的解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41671213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com