Class A 有字段 a1、a2;Class B 有 b1、b2。
a1 變化 → 影響 b1;b2 變化 → 影響 a2。雙向依賴,需解耦。
**雙方不直接持有引用**,通過中介者註冊/發布事件。
// 事件定義
class A1ChangedEvent { public final String newValue; ... }
class B2ChangedEvent { public final int newValue; ... }
// 中介者 (單例或依賴注入)
class Mediator {
private final List> subscribers = new CopyOnWriteArrayList<>();
public void subscribe(Consumer handler) { subscribers.add(handler); }
public void publish(Event event) { subscribers.forEach(h -> h.accept(event)); }
}
// A 類
class A {
private String a1;
private final Mediator mediator;
public A(Mediator m) { this.mediator = m;
m.subscribe(e -> { if (e instanceof B2ChangedEvent) this.a2 = computeA2(e); });
}
public void setA1(String v) {
this.a1 = v;
mediator.publish(new A1ChangedEvent(v));
}
}
// B 類
class B {
private int b2;
private final Mediator mediator;
public B(Mediator m) { this.mediator = m;
m.subscribe(e -> { if (e instanceof A1ChangedEvent) this.b1 = computeB1(e); });
}
public void setB2(int v) {
this.b2 = v;
mediator.publish(new B2ChangedEvent(v));
}
}
CopyOnWriteArrayList 或 RxJava/Reactor 流式處理。// 不推薦
class A { B b; void setA1() { b.onA1Change(); } }
class B { A a; void setB2() { a.onB2Change(); } }
// 循環依賴、難測試、死鎖風險
eventBus.register(this) + @Subscribe 註解。applicationContext.publishEvent() + @EventListener。PublishSubject 熱流,支持背壓、操作符組合。DomainActionEvent (如 OrderCreatedEvent)。