Created
August 23, 2013 06:23
-
-
Save dodola/6316103 to your computer and use it in GitHub Desktop.
Java 观察者模式示例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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