public ConcreteObserver(Subject subject) { this.concreteSubject = subject; this.concreteSubject.registerObserver(this); }
@Override public void update(Subject sub, Object obj) { System.out.println("Subject is " + sub.toString() + " Data is " + obj.toString()); } }
Main:
1 2 3 4 5 6 7 8 9
public class Main { public static void main(String[] args) { ConcreteSubject subject = new ConcreteSubject(); Observer observer = new ConcreteObserver(subject); subject.setData(new HashMap<Integer, Integer>(){{put(1, 1);}}); subject.setData(new HashMap<Integer, Integer>(){{put(2, 2);}}); subject.setData(new HashMap<Integer, Integer>(){{put(3, 3);}}); } }
输出结果:
1 2 3
Subject is observer_pattern.ConcreteSubject@610455d6 Data is {1=1} Subject is observer_pattern.ConcreteSubject@610455d6 Data is {2=2} Subject is observer_pattern.ConcreteSubject@610455d6 Data is {3=3}