I would like to listen your opinions about applying observer pattern.
My goal is to implement one concrete observer class that can listen multiple observable.
If I develop each different observer like below, then it would be simple like below.
public class ConcreteObserver implements EventObserverA , EventObserverB {
updateEventA(EventA event) {}
updateEvetnB(EventB event) {}
}
In this case, I should write many different observer/observable classes/interfaces with almost same code snippet inside.
To avoid hassle like above, I'd like to generify observer/ but as you guys know multiple inheritance rule does not allow code like below.
public class ConcreteObserver implements Observer<EventA> , Observer<EventB> {
update(EventA event) {}
update(EventB event) {}
}
Because I have at least double digit Observable events to observe in one concrete observer, I want to avoid implementing every observer/observable pair separately if possible.
I might guess there could be a better pattern for this case than observer pattern, since observer pattern is designed for n:1 observer:observable while my case needs 1:n observer:observable .
Do you guys have any idea/suggestion for this case?
With the magic of Java 8, your ConcreteObserver
doesn't necessarily have to actually implement Observer<EventA>
and Observer<EventB>
; if you write something like this:
public class ConcreteObserver {
observeEventA(EventA event) {}
observeEventB(EventB event) {}
}
then you can use ::updateEventA
or ::updateEventB
on a ConcreteObserver
instance to get a method that is automatically convertible to the Observer<EventA>
or Observer<EventB>
functional interface. For example, you can write any of the following:
Observer<EventA> eventAObserver = concreteObserver::updateEventA;
Observer<EventB> eventAObserver = new ConcreteObserver()::updateEventB;
observerRegistry.register(EventA.class, concreteObserver::updateEventA);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.