您如何设计代码,以便使观察者模式包含多个主题并想知道发生了什么?
显而易见的解决方案是
interface SubjectOneObserver {
void update(SomeStateModel m);
}
interface SubjectTwoObserver {
void update(SomeStateModelTwo m2);
}
然后具体些
class Concrete implements SubjectOneObserver, SubjectTwoObserver {...}
不太好,将创建许多接口。最好的方法是什么?
答案 0 :(得分:1)
我将使用现有接口或通用接口作为匿名类(最好是lambda),而不是创建许多接口并直接在类中实现它们。
Java(8+)已经为您的用例提供了一个名为Consumer的接口:https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html
class Observable {
// there are better ways than using a list, but it shows how the subject would work
private List<Consumer<SomeStateModel>> subjectOne = new ArrayList();
private List<Consumer<SubjectTwoObserver>> subjectTwo = new ArrayList();
subscribeOne(Consumer<SomeStateModel> observer) {
subjectOne.add(observer);
}
subscribeTwo(Consumer<SubjectTwoObserver> observer) {
subjectTwo.add(observer);
}
triggerOne(SomeStateModelTwo state) {
subjectOne.forEach(c -> c.accept(state));
}
....
}
class Concrete {
Concrete(Observable instanceToObserve) { // i put that in the constructor, no idea were you get your instance from
instanceToObserve.subscribeOne(state -> {
// this will get called when subjectOne is triggered
})
instanceToObserve.subscribeTwo(state -> {
// this will get called when subjectTwo is triggered
})
}
}
您的问题非常广泛,目前尚不清楚您实际上要达到什么目的。特别是您如何使观察者订阅该主题。如果您使用大量的可观察对象和对象,那么也许您应该使用已经具备所有功能的库,例如RxJava:https://github.com/ReactiveX/RxJava