import java.util.Observable;
import java.util.Observer;
public class Test {
public static void main(String[] args) {
Thief thief = new Thief();
Guard guard = new Guard();
thief.addObserver(guard);
thief.steal();
}
}
class Guard implements Observer{
public void catchThief(){
System.out.println("caught!");
}
@Override
public void update(Observable o, Object arg) {
String msg = (String) arg;
System.out.println(msg);
catchThief();
}
}
class Thief extends Observable{
public void steal(){
this.setChanged();
this.notifyObservers("steal");
}
}
观察者模式
最新推荐文章于 2021-02-01 00:00:00 发布