Last active
October 30, 2023 20:39
-
-
Save MariusVolkhart/4601936 to your computer and use it in GitHub Desktop.
Observer Pattern for Java implemented using Interfaces and Generics.This avoids having to cast or use instanceof and allows us to continue using other classes. The drawback is that we have to implement our own boilerplate methods every time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Provides the Observable interface for the Observer Pattern.<br/> | |
* <br/> | |
* Generics explained:<br/> | |
* T - The type of the argument that this Observable will push to the Observers.<br/> | |
* <br/> | |
* Using this interface for the Observer pattern prevents the need for type casting and for using | |
* {@code instanceof} to discover types. | |
*/ | |
public interface Observable<T> { | |
void register(Observer<T> observer); | |
void unregister(Observer<T> observer); | |
void notifyObservers(T arg); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Provides the Observer interface for the Observer Pattern.<br/> | |
* <br/> | |
* Generics explained:<br/> | |
* T - The type of the argument that the Observable will push to this Observer.<br/> | |
* <br/> | |
* Using this interface for the Observer pattern prevents the need for type casting and for using | |
* {@code instanceof} to discover types. | |
*/ | |
public interface Observer<T> { | |
void update(T arg); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment