Design pattern Observer, using Java 8 and Java 9+.
This tutorial shows one way to implement the observer pattern using Java 8 and Java 9+.
Let’s remember what problem this pattern solve. The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods, source.
Then, this is about how the pattern can be written using Java 8 and 9+.
Observer diagram from Wikipedia.
Java 8
With Java 8 is possible implement this pattern using the java.util.Observable. For didactics reasons the interface java.util.Observer will be not used instead was created a new one.
Following the picture below, in Java 8 the pattern was made in this way. The main class, omitted here, attach 3 observers, send a message, remove one observer and then send another message.
Main code
Java 9+
With Java 9, this topic can be handled using the Flow Api, below see Api class descriptions.
Flow.Processor : A component that acts as both a Subscriber and Publisher.
Flow.Publisher : A producer of items received by Subscribers.
Flow.Subscriber : A receiver of messages.
Flow.Subscription: Message control linking a Flow.Publisher and Flow.Subscriber.
Apart from used the Flow Api you can use Rx Api, since this tutorial is to show a way to implement this pattern, you can try another approach.
Below see the UML diagram used in this example, then the log.
Main code
Conclusion
Using Java 8 is easiest to implement the observer pattern even though the classes Observer and Observable were mark as deprecated, since you’re using Java 9+ try the Flow Api or even Rx Api.
The Flow Api in another hand is ready for reactive streams, more details in this document from Oracle Community.
Source → These code are available in my GitHub account.