Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 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 Reply

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...