views:

86

answers:

3

Hello. I have 4 classes, that describe state diagram. Node, Edge, ComponentOfNode, 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 form ComponentOfEdge. The user can change ComponentsOfNode. I need this change spreads to all Edge. Hw to do it? I expect the observer should be used. Can you give me example in pseudocode please?

+2  A: 

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 (unfortunatly on a Swing example, leading to confusion) in the official Java tutorial.

Riduidel
A: 

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);
    }

  }

} 
danben
A: 

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);
    }
ibrahimyilmaz
You forgot the registerListener(INodeListener listener) :)
extraneon
hmm you are right=)
ibrahimyilmaz