0

I'm looking for a way to send an event carrying an object in its "payload". My goal is to send this event somewhere in an object of class Sender, and have class Receiver listen for these events, react when it detects one, and do something with the object carried by the event.

At the moment, I'm doing this in a way that I believe is not very elegant, but works fine. I'm using a PropertyChange event. This event is usually used to signal changes in a field of an object, if I have understood things correctly, and this is the reason I think my usage of it is not elegant. This is what I do.

In class Sender I have:

support.firePropertyChange("dummyName", null, objectToBeSent);

Where support is a field of Sender that has been initialized as follows:

support = new PropertyChangeSupport(this);

So basically what I do is to signal the change of a dummy property that doesn't exist, and I signal that the old value of the property is null, and the new one is the reference to the object I want to send to the Receiver.

In class Receiver, which implements PropertyChangeListener I have:

@Override
public void propertyChange(PropertyChangeEvent event) {
    if ("dummyName".equals(event.getPropertyName())) {
        // do something with event.getNewValue()...
    }
}

Is there some more adequate Java class/utility that allows me to accomplish the same task in a more elegant way? Thank you in advance.

Tomoms
  • 1
  • 1
  • You probably need to define what you mean by "more elegant". That sounds like an opinionated question. But you can implement the Observer pattern pretty easily without the java.beans dependencies if that's your goal. – jaco0646 Oct 11 '21 at 16:18
  • @jaco0646 I think this is not very elegant because PropertyChange events are meant to be used to signal a change in a field of an object (by giving information on the name of the field that changed, and its old & new values). I am exploiting them to do something that is totally different, in fact my propertyName string is a dummy name and the old value is always null, because the "new value" parameter alone serves my needs. I'm not using the Observer pattern because I read that it is deprecated since Java 9. – Tomoms Oct 11 '21 at 20:13
  • This [comment](https://stackoverflow.com/questions/46380073/observer-is-deprecated-in-java-9-what-should-we-use-instead-of-it#comment79728752_46381645) is critically important. There is nothing wrong with the Observer pattern, and there are numerous ways to implement it. Java's old implementation happens to be poor. The pattern itself is perfectly fine, and pretty easy to implement on your own. – jaco0646 Oct 11 '21 at 21:56
  • 1
    @jaco0646 got it, thanks. I am now implementing communication between the two classes via events and listeners. – Tomoms Oct 14 '21 at 13:33

0 Answers0