设计模式之观察者模式

观察者模式

  1. 观察者模式结构图

  2. 示例代码

// 抽象主题
public abstract class Subject {
    protected List<Observer> observers = new ArrayList<>();

    protected Event event;

    public boolean attach(Observer observer){
        return !observers.contains(observer) && observers.add(observer);
    }

    public boolean detach(Observer observer){
        return observers.contains(observer) && observers.remove(observer);
    }

    public void setEvent(Event event){
        this.event = event;
    }

    public abstract void notifies();
}

// 具体主题
public class ConcreteSubject extends Subject{
    @Override
    public void notifies() {
        observers.forEach(a -> a.update(event));
    }
}


// 事件
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Event {
    private Object source;
    private Observer target;
    private String trigger;
    private Long time;
}

// 抽象观察者
public interface Observer {

    void update(Event event);
}

// 具体观察者A
public class ConcreteObserverA implements Observer{
    @Override
    public void update(Event event) {
        System.out.println("具体观察者A接受到观察事件:" + event.getTrigger());
    }
}

// 具体观察者B
public class ConcreteObserverB implements Observer{
    @Override
    public void update(Event event) {
        System.out.println("具体观察者B接受到观察事件:" + event.getTrigger());
    }
}

// 测试
public class ObserverTest {

    public static void main(String[] args) {
        Subject subject = new ConcreteSubject();
        Event event = new Event();
        event.setSource(subject);
        event.setTime(System.currentTimeMillis());
        event.setTrigger("被观察对象发生了变化......");
        subject.setEvent(event);
        subject.attach(new ConcreteObserverA());
        subject.attach(new ConcreteObserverB());
        subject.notifies();
    }
}

  1. 总结:

    优点:观察者与被观察者是松耦合的,符合依赖倒置原则,且实现了一对多的通信机制;

    缺点:如果观察者数量过多,则耗时较长;且事件通知呈线性关系,若其中一个观察者卡壳,则影响后续观察者接受事件;若观察者与被观察者存在循环依赖,则可能造成两者之间的循环调用,导致系统崩溃.

posted @ 2021-04-17 11:46  justKen  阅读(37)  评论(0编辑  收藏  举报