设计模式之观察者模式

2023-02-13  本文已影响0人  Tinyspot

1. 观察者模式

观察者模式的核心是将观察者与被观察者解耦,以类似消息/广播发送的机制联动两者,使被观察者的变动能通知到感兴趣的观察者们,从而做出相应的响应

1.1 组成

2. 示例

注册观察者,订阅主题(subject)

/**
 * 主题:被观察者
 */
public interface ISubject {
    void notify(String event);
    boolean register(IObservable observable);
    boolean remove(IObservable observable);
}
public class ConcreteSubject implements ISubject {

    private List<IObservable> observables = new ArrayList<>();

    @Override
    public boolean register(IObservable observable) {
        return !this.observables.contains(observable) && this.observables.add(observable);
    }

    @Override
    public boolean remove(IObservable observable) {
        return this.observables.remove(observable);
    }

    @Override
    public void notify(String event) {
        for (IObservable observable : this.observables) {
            observable.handler(event);
        }
    }
}

Observer 接口,它将不同的观察者聚合在一起

/**
 * 观察者:监听被观察者的变化
 */
public interface IObservable {
    void handler(String event);
}

public class ConcreteObserverA implements IObservable {
    @Override
    public void handler(String event) {
        System.out.println("concrete observer A: " + event);
    }
}

public class ConcreteObserverB implements IObservable {
    @Override
    public void handler(String event) {
        System.out.println("concrete observer B: " + event);
    }
}

测试:

@Test
public void test() {
    ISubject subject = new ConcreteSubject();
    subject.register(new ConcreteObserverA());
    subject.register(new ConcreteObserverB());
    subject.notify("test");
}
上一篇 下一篇

猜你喜欢

热点阅读