Skip to content

Instantly share code, notes, and snippets.

@dodola
Created August 23, 2013 06:23
Show Gist options
  • Save dodola/6316103 to your computer and use it in GitHub Desktop.
Save dodola/6316103 to your computer and use it in GitHub Desktop.
Java 观察者模式示例
import java.util.Observable;
import java.util.Observer;
/*
* Java 观察者模式示例
*/
class MyDataObservable extends Observable {
private String data;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
this.setChanged();
this.notifyObservers();
}
}
class MyDataObserver implements Observer {
@Override
public void update(Observable arg0, Object arg1) {
MyDataObservable data = (MyDataObservable) arg0;
System.out.println("data has changed:" + data.getData());
}
}
public class ObserverMe {
public static void main(String[] args) {
MyDataObservable data = new MyDataObservable();
MyDataObserver observer = new MyDataObserver();
data.addObserver(observer);
data.setData("data1");
data.setData("data2");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment