观察者模式
GuoJun 2022-05-23 设计模式
# 简介
当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知依赖它的对象。观察者模式属于行为型模式。
# 实现
- 创建Subject类
public class Subject {
private List<Observer> observers = new ArrayList<>();
private int state;
public int getState(){
return state;
}
public void setState(int state){
this.state = state;
notifyAllObservers();
}
private void notifyAllObservers() {
for (Observer observer : observers) {
observer.update();
}
}
public void attach(Observer observer) {
observers.add(observer);
}
}
- 创建Observer类
public abstract class Observer {
protected Subject subject;
public abstract void update();
}
- 创建实体观察者类
public class BinaryObserver extends Observer{
public BinaryObserver(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println("二进制: "+Integer.toBinaryString(subject.getState()));
}
}
public class OctalObserver extends Observer{
public OctalObserver(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println("八进制: "+Integer.toOctalString(subject.getState()));
}
}
public class HexObserver extends Observer {
public HexObserver(Subject subject) {
this.subject = subject;
this.subject.attach(this);
}
@Override
public void update() {
System.out.println("十六进制: "+Integer.toHexString(subject.getState()));
}
}
- 使用Subject和实体类观察者对象
public class ObserverPatternDemo {
public static void main(String[] args) {
Subject subject = new Subject();
new HexObserver(subject);
new OctalObserver(subject);
new BinaryObserver(subject);
System.out.println("第一次设置15");
subject.setState(15);
System.out.println("=======================");
System.out.println("第二次设置10");
subject.setState(10);
}
}