Where is the place to register listeners

I am working on a project that makes heavy use of the observer pattern. Many classes are used as event / message listeners. Usually the listening class is registered in the constructor, and I see two problems with this:

  • We do the work in the constructor
  • The class becomes dependent on the observed class, although it is only interested in the event itself.

should registration be registered by the hearing class or should it be some other?

+5
source share
1 answer

Signing from the constructor can cause problems for inheritance. Say we have code that looks like this:

public class Parent { public Parent(EventObject source) { // initialize parent ... source.subscribe(this::someMethod); } public void someMethod() { ... } ... } public class Child extends Parent { public Child(EventObject source) { super(source); // initialize child ... } ... } 

Child ctor calls the Parent ctor, which registers with the event source. However, note that the Child object is not initialized when the Parent registered. If the event source is updated before the Child ctor completes, your code may behave very strange.

An easy way to avoid this problem is to create a subscription within factory methods, which hides ctors.

 public class Parent { public static Parent newInstance(EventObject source) { Parent p = new Parent(); source.subscribe(p::someMethod); return p; } protected Parent() { // initialize parent ... } public void someMethod() { ... } ... } public class Child extends Parent { public static Child newInstance(EventObject source) { Child c = new Child(); source.subscribe(c::someMethod); return c; } protected Child() { super(); // initialize child ... } ... } 
+3
source

Source: https://habr.com/ru/post/1246869/


All Articles