Note that there are some explanatory texts on larger screens.

plurals
  1. POProper coupling for multiple listeners that need to accessed shared state data
    primarykey
    data
    text
    <p>Working with a traditional listener callback model. I have several listeners that collect various stuff. Each listener's collected stuff is inside the listener in internal structures.</p> <p>The problem is that I want some of the listeners to be aware of some of the "stuff" in the other listeners.</p> <p>I enforce listener registration order, so if I knowingly register events in some order a later listener can be sure that a previously listener updated its stuff and somehow access it to do more stuff. </p> <p>My first attempt at this is to have each listener store a reference to the listeners upon which it depends. So I register listeners in the order of those without dependencies to those with prior-registered dependencies, and then set the references between the listeners in various methods.</p> <p>I am starting to realize how bad this feels and I was wondering if somehow has been down this road before. What would be a more appropriate pattern when one of the listeners needs to access stuff in another?</p> <p>Here is some pseudocode to illustrate:</p> <pre><code>interface Listener { onEvent(char e); } class A implements Listener { private int count; public void onEvent(char e) { if(e == 'a') count++; } public int getCount() { return count; } } class B implements Listener { private int count; // private A a; // private void setA(A a) { this.a = a; } public void onEvent(char e) { if(e == 'b') count++; } public int getCount() { return count; } public int getAPlusBCount() { // We know B count, but we don't know A so how would we change this // so B is A aware? Or not even aware, just somehow coupled? This // is the question // return a.getCount() + count; } public void doConditionalHere() { // Do some condition in B that relies on the state of data in A int acount = 0; // a.getCount(); ??? if(acount % 2 == 0) { this.count--; } } } class Run { A a = new A(); B b = new B(); List listeners = new List(); listeners.add(a); listeners.add(b); // The ugly way I add coupling right now is to keep a reference to A // inside B. It's commented out because I am hoping there is a more intelligent approach // b.setA(a); for(char c : "ababbabab") { for(listener : listeners) { listener.onEvent(c); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload