基于util包的观察者模式demo
import java.util.Observable;
import java.util.Observer;
/**
* @author by yze on 2019/4/19
* @see
* @since
*/
public class ObserverTest {
static class WeatherData extends Observable {
private int arg1;
private int arg2;
public WeatherData(int arg1, int arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
}
public void setMeasurements(int arg1, int arg2) {
this.arg1 = arg1;
this.arg2 = arg2;
measureDataChanged();
}
public void measureDataChanged() {
setChanged();
notifyObservers();
}
public int getArg1() {
return arg1;
}
public void setArg1(int arg1) {
this.arg1 = arg1;
}
public int getArg2() {
return arg2;
}
public void setArg2(int arg2) {
this.arg2 = arg2;
}
}
static class Observer1 implements Observer {
private Observable observable;
public Observer1(Observable observable) {
this.observable = observable;
observable.addObserver(this);
}
@Override
public void update(Observable obs, Object arg) {
if (obs instanceof WeatherData) {
System.out.println(((WeatherData) obs).getArg1() + " " + ((WeatherData) obs).getArg2());
}
}
}
static class Observer2 implements Observer {
private Observable observable;
public Observer2(Observable observable) {
this.observable = observable;
observable.addObserver(this);
}
@Override
public void update(Observable obs, Object arg) {
if (obs instanceof WeatherData) {
System.out.println("this is observer 2 :" + ((WeatherData) obs).getArg1() + " " + ((WeatherData) obs).getArg2());
}
}
}
public static void main(String[] args) {
WeatherData weatherData = new WeatherData(1, 2);
Observer1 observer1 = new Observer1(weatherData);
Observer2 observer2 = new Observer2(weatherData);
weatherData.setMeasurements(3, 4);
}
}
网友评论