Reputation: 974
Assume there is a module A such that module B and C depend on it. Module A support listener pattern i.e. modules like B and C can listen to events generated by A. Therefore module A is decoupled from its listeners. Now we want to have some set of contracts (interface in Java) that can collectively define the contract of module A.
The problem is to insert listeners into the contract. Should I add functions like "public addListener(Listener listener)" into the contract? Other way is to use abstract class that implements listener part and leave other functions as abstract. I really do not want to extend classes since at some point if we decide to implement two contract in a single class then it is impossible. Can you discuss the above cases and any insight into related topic is appreciated.
Why I want listeners in contract? This is because modules that listen to A should not break up if someday someone re-writes module A. If this is not a good idea then let me know.
EDIT : One of the problem is I want to make listener/events part of the contract so that future changes/re-implementations can be done easily. It should not happen that a particular event E was being fired earlier by module A but now new implementation made it event B because the programmer was not aware of events (as it was not a part of contract). One issue with this approach is that I am forcing programmer to fire these events and use event based system.
Upvotes: 1
Views: 175
Reputation: 916
Ovserver pattern is a great way to de-couple.
Adding addListener and removeListeners method in the observalble class is not a good idea because it will result into code duplication (if and abstract implementation is not used).
A better solution will be to define Registration class which has two method addListener, removeListener and fireEvent method. In this scenario, the Obeservable class will just implement the interface eg MyObservable and thats it.
Following link will help you more regarding Registration classes : EventBus in Java
Upvotes: 2
Reputation: 234867
I would definitely define A in terms of a listener interface, with addListener
(and possibly removeListener
) public methods and a protected notifyListeners
method (or possibly more, depending on the complexity of the listener interface).
Note that modules B and C might also not implement the listener interface; they could use separate listener objects (perhaps even anonymous inner classes).
Generally speaking, I would not implement an abstract listener class; leave that up to each listener implementation. An exception would be if the listener interface declared a lot of methods, not all of which would be applicable to any particular client. Then it might be useful to implement a base listener class that does nothing for each method. This approach can be seen, for instance, with the java.awt.MouseAdapter
class, which implements various mouse-related listener interfaces.
Upvotes: 2