开发者

how to implement this observer pattern?

开发者 https://www.devze.com 2022-12-24 00:43 出处:网络
I have 4 classes, that describe state diagram. Node, Edge, ComponentOfNode and ComponentOfEdge. ComponentOfEdge compounds from ComponentsOfNode. Node can have 0..n outgoing edges. Edge can have only

I have 4 classes, that describe state diagram. Node, Edge, ComponentOfNode and ComponentOfEdge.

ComponentOfEdge compounds from ComponentsOfNode. Node can have 0..n outgoing edges. Edge can have only 2 Nodes.

Edge should be able to offer ComponentOfNode, but only from Nodes that Edge has, in the form of ComponentOfEdge.

The user can change ComponentsOfNode. I need this change spreads to all Edges. How would I do it? I expect the observer pattern should be used.

Can you give me an exam开发者_高级运维ple in pseudo-code please?


You know, in Java, the best example of an Observer/Observable pattern (and the easies to use in non-Swing code) is the propertyChange[Event/Listener/Support] trinity. It is documented (unfortunately on a Swing example, leading to confusion) in the official Java tutorial.


Observer is a pretty simple pattern. All you need to do is implement a method in the observing class that is called by the observed class on a change.

In your case, you might have:

class Edge {
  // class definition

  public void nodeChanged(Node changed) {

    // do stuff

   }
}

class Node {
  // class definition

  protected void onChange() {

    for (Edge e : myEdges) {
      e.nodeChanged(this);
    }

  }

} 


hi make one interface or use java's default observer interface.I advice you to implement your observer.

interface INodeListener{
void update(Object obj);
}

Node Listeners should be implement this interface. in your node you should hold it's listener.When changed Node make invoke listener method.

    public void invokeListener() {
       for(INodeListener listener:listeners)
        listener.update(yourVariable);
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消