Java開発でObserverの観察対象を定義するサンプルプログラム

コード下記:
import java.util.Observable;
public class SubjectObservable extends Observable{
public void changeDate(){
System.out.println(“日付を変更した");
this.setChanged();
}
}
class Subject{
SubjectObservable f = new SubjectObservable();
public void registerObserver(java.util.Observer o){
f.addObserver(o);
}
void changeSubject(){
f.changeDate();
//観察者に通知
f.notifyObservers();
}
}
//観察者1
class SubjectObserver implements java.util.Observer {
public void update(Observable o, Object arg) {
SubjectObservable subject=(SubjectObservable) o;
System.out.println(“観察者1は仕事中 “);
}
}
//観察者2
class SubjectObserver2 implements java.util.Observer {
public void update(Observable o, Object arg) {
SubjectObservable subject=(SubjectObservable) o;
System.out.println(“観察者2は仕事中");
}
}
main処理コード
public static void main(String args[]){
Subject sbt = new Subject();
SubjectObserver or = new SubjectObserver();
SubjectObserver2 or2 = new SubjectObserver2();
sbt.registerObserver(or2);
sbt.registerObserver(or);
sbt.changeSubject();
}

Java

Posted by arkgame