Skip to content

Instantly share code, notes, and snippets.

@MariusVolkhart
Last active October 30, 2023 20:39
Show Gist options
  • Save MariusVolkhart/4601936 to your computer and use it in GitHub Desktop.
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.
/**
* 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);
}
/**
* 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