Generic Listener

Context

Problem Forces Solution

Define a base class with an abstract no-arg no-return method, an input member variable, an output member variable, and at least one 'invocation' method, which will populate the input, call the abstract method, and return the contents of the output. Use this base class anywhere you would normally use a typed listener, using an adapter as necessary. Call the invocation method to notify the listener, passing in the context if necessary.

[A question--why would you use member variables? Why wouldn't the abstract method just take the input context Object as a parameter and return the resulting output Object? Wouldn't this avoid the clone-on-invocation requirement below?]

Example

 class Something{
     private Method listener;
     public void somethingCausingAnEvent(){
listener.invoke();
     }

public void doWhenSomethingHappens(Method listener){ this.listener = listener; } }

class ExitProgram extends Method{ protected void method(){ System.exit(0); } }

class PrintObject extends Method{ protected void method(){ System.out.println(parameter); } }

class Notification extends Method{ public synchronized void doWait(){ try{ wait(); }catch(InterruptedException ignore){ } }

protected void method(){ notifyAll(); } }

class Method { private Object parameter; private Object returnValue; public Object invoke(){ invoke(null); }

public Object invoke(Object parameter){ this.parameter = parameter; method(); return returnValue; }

protected abstract void method(); }

Resulting Context Known Uses

Currently it's making appearances in my personal Collections implementations (forEach() type stuff), listeners, instead of the occasional global variable (pass in a method which will return the current FooBar, even if you don't know which one it'll be yet). Don't think this quite qualifies as three distinct uses though :)

Related Patterns

-- WilliamUnderwood


CategoryJava


EditText of this page (last edited December 21, 2014) or FindPage with title or text search