设计模式—观察者模式

介绍

代码

观察者父类

只有一个属性 subject 表示订阅的主题。update 方法用于更新观察者本身

public abstract class Observer {
    protected Subject subject;
    
    public abstract void update();
}

主题类

主题类 Subject 直到自己的订阅者们,每当主题状态改变的时候就通知所有订阅者。

public class Subject {
    private List<Observer> observers = new ArrayList<>();

    private int state;

    public void addObserver(Observer observer){
        this.observers.add(observer);
    }

    public void notifyAllObservers(){
        for (Observer observer : observers) {
            observer.update();
        }
    }
    
    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
        this.notifyAllObservers();
    }
}

观察者实现类

有三个观察者实现类:BinaryObserverHexaObserverOctalObserver

public class BinaryObserver extends Observer{
    public BinaryObserver(Subject subject) {
        this.subject = subject;
        this.subject.addObserver(this);
    }

    @Override
    public void update() {
        System.out.println("BinaryObserver.update: " + Integer.toBinaryString(subject.getState()));
    }
}
public class HexaObserver extends Observer{
    public HexaObserver(Subject subject) {
        this.subject = subject;
        this.subject.addObserver(this);
    }

    @Override
    public void update() {
        System.out.println("HexaObserver.update: " + Integer.toHexString(subject.getState()));
    }
}
public class OctalObserver extends Observer{
    public OctalObserver(Subject subject) {
        this.subject = subject;
        this.subject.addObserver(this);
    }

    @Override
    public void update() {
        System.out.println("OctalObserver.update: " + Integer.toOctalString(subject.getState()));
    }
}

测试

public class ObserverTest {

    @Test
    void test(){
        Subject subject = new Subject();

        new HexaObserver(subject);
        new OctalObserver(subject);
        new BinaryObserver(subject);

        System.out.println("First state change: 15");
        subject.setState(15);
        System.out.println("Second state change: 10");
        subject.setState(10);
    }
}
posted @ 2023-12-20 13:52  Frodo1124  阅读(12)  评论(0编辑  收藏  举报