被观察者(事件源)
package com.dwz.concurrency2.chapter4;
import java.util.ArrayList;
import java.util.List;
public class Subject {
private List<Observer> observers = new ArrayList<>();
private int state;
public int getState() {
return this.state;
}
public void setState(int state) {
if(state == this.state) {
return;
}
this.state = state;
notifyAllObserver();
}
public void attach(Observer observer) {
observers.add(observer);
}
private void notifyAllObserver() {
observers.stream().forEach(Observer::update);
}
}
观察者抽象类
package com.dwz.concurrency2.chapter4;
public abstract class Observer {
protected Subject subject;
public Observer(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}
public abstract void update();
}
观察者1-二进制观察者
package com.dwz.concurrency2.chapter4;
public class BinaryObserver extends Observer {
public BinaryObserver(Subject subject) {
super(subject);
}
@Override
public void update() {
System.out.println("Binary String:" + Integer.toBinaryString(subject.getState()));
}
}
观察者2-八进制观察者
package com.dwz.concurrency2.chapter4;
public class OctalObserver extends Observer {
public OctalObserver(Subject subject) {
super(subject);
}
@Override
public void update() {
System.out.println("Octal String:" + Integer.toOctalString(subject.getState()));
}
}
测试类
package com.dwz.concurrency2.chapter4;
public class ObserverClient {
public static void main(String[] args) {
final Subject subject = new Subject();
new BinaryObserver(subject);
new OctalObserver(subject);
System.out.println("==================");
subject.setState(10);
System.out.println("==================");
subject.setState(10);
System.out.println("==================");
subject.setState(15);
}
}