编写一个程序,声明一个类,该类继承自Observable(因此该类是个主题角色),有一个int类型的变量,初始值为10,编写一个for循环,将该数字每次递减1,一直到0位置,当每次变化时,都将该数字传递给它的观察者。观察者会打印出该数字;第二个观察者在该数字变为5之后开始打印数字
import java.util.Observable;
import java.util.Observer;
class BeingWatched extends Observable
{
void counter(int number)
{
for(; number >= 0 ; number--)
{
this.setChanged();
this.notifyObservers(number);
}
}
}
class Watcher1 implements Observer
{
@Override
public void update(Observable o, Object arg)
{
System.out.println("count is: " + arg);
}
}
class Watcher2 implements Observer
{
@Override
public void update(Observable o, Object arg)
{
if(((Integer)arg).intValue()<= 5)
{
System.out.println("cout is : " + arg);
}
}
}
public class TwoObservers
{
public static void main(String[] args)
{
BeingWatched watched = new BeingWatched();
Watcher1 watcher1 = new Watcher1();
Watcher2 watcher2 = new Watcher2();
watched.addObserver(watcher1);
watched.addObserver(watcher2);
watched.counter(10);
}
}