这是一个我试图找出的例子:
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; } 返回null; } } public class IntegerAdder implements Observer { private IntegerDataBag bag; public IntegerAdder(IntegerDataBag包){ this.bag = bag; bag.addObserver(this); } public void update(Observable o,Object arg){ if(o == bag){ System.out.println( IntegerDataBag已更改); } } }
bag.addObserver()只能由于 IntegerDataBag 扩展可观察?
这个观察者在哪里添加?什么是创建和在哪里?
setChanged()和 notifyObservers()?
我不明白更新方法; arg 代表什么?为什么我需要检查 o == bag ?为什么我会更新另一个可观察的?
为什么我还需要这个观察者?
解决方案
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"); } } }
The bag.addObserver() can be made only because IntegerDataBag extends Observable?
Where is this observer being add to? What is being created and where?
What is the difference between setChanged() and notifyObservers()?
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?
Why should I need this observer anyway?
解决方案
更多推荐
在Java中可以观察到
发布评论