简体   繁体   中英

does the Constructor of an Observer needs the Observable as parameter?

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.

Not necessarily. You usually do this to register the oberver to an observable. But you can do this from outside as well. the pro of using with constructor approach is you wont miss to register the observer while coding, otherwise both approaches are fine.

With constructor:

  public MyObserver(MyObservable myObservable) {
      myObservable.register(this);
  }

  Main code: 
  MyObservable observable1 = new MyObservable();

        Observer obj1 = new MyObserver(observable1 );
        Observer obj2 = new MyObserver(observable1 );
        Observer obj3 = new MyObserver(observable1 );

Something like this without constructor:

        Observer obj1 = new MyObserver();
        Observer obj2 = new MyObserver();
        Observer obj3 = new MyObserver();

        //register observers to the subject
        observable1.register(obj1);
        observable1.register(obj2);
        observable1.register(obj3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM