Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
826 views
in Technique[技术] by (71.8m points)

oop - Observable in Java

I'm trying to understand the Observer and the Observable.

Here's an example that I'm trying to figure out:

public class IntegerDataBag extends Observable implements Iterable<Integer> {

    private ArrayList<Integer> list= new ArrayList<Integer>();

    public void add(Integer i){
        list.add(i);
        setChanged();
        notifyObservers();
    }

    public Iterator<Integer> iterator(){
        return list.iterator();
    }

    public Integer remove (int index){
        if (index< list.size()){
            Integer i = list.remove(index);
            setChanged();
            notifyObservers();
            return i;
        }
        return null;
    }

}

public class IntegerAdder implements Observer {

    private IntegerDataBag bag;

    public IntegerAdder(IntegerDataBag bag) {
        this.bag = bag;
        bag.addObserver(this);
    }

    public void update(Observable o, Object arg) {
        if (o == bag) {
            System.out.println("The contents of the IntegerDataBag have changed");
        }
    }

}
  1. The bag.addObserver() can be made only because IntegerDataBag extends Observable?

  2. Where is this observer being add to? What is being created and where?

  3. What is the difference between setChanged() and notifyObservers()?

  4. I don't understand the update method; what does arg stand for? Why do I need to check that o==bag? Why would I update another observable?

  5. Why should I need this observer anyway?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. Yes. addObserver is a method in the Observable abstract class. See Observable in the Java documentation.
  2. It is added to a list in Observable.
  3. A call to notifyObservers will do nothing until setChanged is set.
  4. You might have multiple Observables in the same application.
  5. Observer is a common design pattern. The usual example is when you have a Model and multiple Views. Each View is an Observer on the Model; if the Model changes, the Views get updated.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...