单线程观察者模式
/**
* @ClassName:Subject
* @Author:linianest
* @CreateTime:2020/3/23 9:38
* @version:1.0
* @Description TODO: 观察者观察的主题
*/
public class Subject {
List<Observer> observers = new ArrayList<>();
private int state;
public int getState() {
return state;
}
public void setState(int state) {
if (this.state == state)
return;
this.state = state;
notifyAllobserver();
}
public void attach(Observer observer) {
observers.add(observer);
}
private void notifyAllobserver() {
observers.stream().forEach(Observer::update);
}
}
观察者
/**
* 定义观察者内容与方法
*/
public abstract class Observer {
protected Subject subject;
public Observer(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}
abstract void update();
}
2进制
/**
*@ClassName:BinaryObserver
*@Author:linianest
*@CreateTime:2020/3/23 10:27
*@version:1.0
*@Description TODO: 二进制观察者
*/
public class BinaryObserver extends Observer{
public BinaryObserver(Subject subject){
super(subject);
}
@Override
public void update() {
System.out.println("Binary String:"+Integer.toBinaryString(subject.getState()));
}
}
8进制
/**
* @ClassName:BinaryObserver
* @Author:linianest
* @CreateTime:2020/3/23 10:27
* @version:1.0
* @Description TODO: 八进制观察者
*/
public class OctalObserver extends Observer {
public OctalObserver(Subject subject) {
super(subject);
}
@Override
public void update() {
System.out.println("Octal String:" + Integer.toOctalString(subject.getState()));
}
}
观察者客户端
/**
* @ClassName:psvm
* @Author:linianest
* @CreateTime:2020/3/23 11:29
* @version:1.0
* @Description TODO: 观察者模式客户端
*/
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);
}
}