Java listener design template for subscription

I am trying to create a Java system that is similar to the concept of C # delegates.

Here is the basic functionality that I want to achieve:

public class mainform
{
   public delegate onProcessCompleted
//......
    processInformation()
    {
            onProcessCompleted(this);
    }

//......
}


//PLUGIN

public class PluginA
{
        public PluginA()
        {
            //somehow subscribe to mainforms onProcessingCompleted with callback myCallback()
        }

        public void myCallback(object sender)
        {
        }


}

I read this site: http://www.javaworld.com/javaqa/2000-08/01-qa-0804-events.html?page=1

They refer to the implementation of the entire “subscription list” manually. But the code is not a complete example, and I'm so used to C # that I find it hard to understand how I can do this in java.

Does anyone have a working example of this that I could see?

thanks
Stephanie

+3
source share
1 answer

Java ( ); , . .

class Producer {
  // allow a third party to plug in a listener
  ProducerEventListener my_listener;
  public void setEventListener(ProducerEventListener a_listener) {
    my_listener = a_listener;
  }

  public void foo() {
    ...
    // an event happened; notify the listener
    if (my_listener != null) my_listener.onFooHappened(new FooEvent(...));
    ...
  }
}


// Define events that listener should be able to react to
public interface ProducerEventListener {
  void onFooHappened(FooEvent e);
  void onBarOccured(BarEvent e);
  // .. as many as logically needed; often only one
}


// Some silly listener reacting to events
class Consumer implements ProducerEventListener {
  public void onFooHappened(FooEvent e) {
    log.info("Got " + e.getAmount() + " of foo");
  }
  ...
}

...
someProducer.setEventListener(new Consumer()); // attach an instance of listener

, :

someProducer.setEventListener(new ProducerEventListener(){
  public void onFooHappened(FooEvent e) {
    log.info("Got " + e.getAmount() + " of foo");
  }    
  public void onBarOccured(BarEvent e) {} // ignore
});

(, GUI), , , addWhateverListener removeWhateverListener .

, . .

+13

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


All Articles