I am trying to implement an Observer to my anime GUI.
So if an Anime episode is released, then notify the other Observer to update the state of the episode of this specific anime.
And it works.
My Question:
I am trying to understand Observer Pattern and i would like to know if i have to give the Constructor of an Observer the Observable as parameter.
Because i have seen it in some Tutorial and Sites, therefor i am a bit confused.
Best regards
Your George
It does not necessarily need to know about observable at creation.
You can implement it like this (simple example, of course not perfect)
class MyObservable {
private ArrayList<MyObserver> observersList = new ArrayList<>();
public void addObserver(MyObserver observer) {
observersList.add(observer)
// OR observer.addObservable(this) , but it is kinda strange one
}
public void onAnimeReleased() {
// Some other logic, release Anime and etc...
notify();
}
private void notify() {
observersList.forEach((obs) -> obs.notify());
}
}
Note that you can also hold a reference to observer not in a collection.
private MyObserver animeObserver;
To conclude, usually implementing this pattern means you need to implement a way of adding observers to observable and notifying them when it is needed.