dimanche 10 juin 2018

No cast for observer pattern using generics

I was looking to implement an subject-observer pattern where the subject provides its self to the observers when notifying.

public class Subject<T extends Subject> {

    /** suporting stuff for subject */

    private List<Observer<T>> observers = new ArrayList<>();

    protected void doNotify() {
        for(Observer<T> observer : observers) {
            /** This is the line where it gets interesting */
            observer.update((T)this);
        }
    }
}

Practically, this work, however, the compiler gives a Unchecked cast warning on the observer.update((T)this); line.

When reading a bit about this, the compiler is right (surprise surprise) and its even considered as smelly code, as you can write code that actually triggers the ClassCastException.

Now I am looking for a solution that isn't smelly and rock solid. However, the thought that an observer does not need to look for the subject that it is observing is something I really like. Also, I don't really like the observers need to do the cast themselves in their update(). Do you have any suggestion on how to on this one?

Aucun commentaire:

Enregistrer un commentaire