5 public class Main { public static void main(String[]a) { Teacher teacher1 = new Teacher(); Teacher teacher2 = new Teacher(); Student s1 = new Student(); Student s2 = new Student(); teacher1.addObserver(s1); teacher2.addObserver(s2); teacher1.addObserver(s1); teacher2.addObserver(s2); teacher1.createQuestion(); teacher2.createQuestion(); } } Scenario
8 import java.util.Observable; import java.util.Observer; public class Student implements Observer { public String answerQuestion (String question) { return "I am thinking about \'" + question +"\'"; } @Override public void update(Observable o, Object arg) { String x = ((Tutor)o).getQuestion(); String y = this.answerQuestion(x); System.out.println(y); } } Student
10 public class Classroom { public static void main(String[] args) { Student student = new Student(); Tutor tutor = new Tutor(); tutor.addObserver(student); for (int i=0; i<5;i++) tutor.askQuestion(); } } Classroom
12 Java API Java 9 deprecated Observer and Observable implementation in java.util package. It deprecated its own implementation of the concept, not the concept itself Why? serialization and thread safety problems. Solution: PropertyChangeListener from java.beans package.
Winter 2023 Copyright. These slides can only be used as study material for the class CSC308 at Cal Poly. They cannot be distributed or used for another purpose.