java.util.Observer
java.util.Observerを使用したメモ
import java.util.Observer;
import java.util.Observable;
public class Main {
public static void main(String[] args) {
Sample sample = new Sample();
sample.addObserver(new Observer() {
@Override
public void update(Observable observe, Object o) {
System.out.println("changed: " + ((Sample)o).getName());
}
});
sample.setName("hoge");
sample.setName("fuga");
}
public static class Sample extends Observable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
// hasChangedメソッドの返り値がsetChangedを行った後はtrueになる
setChanged();
notifyObservers(this);
}
}
}