I have been trying to make an base observer pattern that uses generic types to create a tightly coupled relationship between the observable object and its subscribers. Take for instance YouTube; a channel would be the observable object and the subscribers would be YouTube users. A YouTube channel can only be subscribed to by a YouTube user and a YouTube user can only subscribe to channels. So, for example, you cannot use a YouTube account to subscribe to a newspaper or a jelly of the month club.
My first idea was just to do something like this:
abstract class Observable<T> where T : Subscriber
abstract class Subscriber<T> where T : Observable
But this does not work because T in both cases would need to extend a class that contains a specific generic type, rendering the generic type useless.
My second idea was to do something like this:
abstract class Observable<T> : IObservable where T : ISubscriber
abstract class Subscriber<T> : ISubscriber where T : IObservable
This works, but it is not completely safe. For example, IObservable
has a method Subscribe(ISubscriber subscriber)
and Observable has the method Subscribe(T t)
The implementation of the interfaces method Subscribe
just casts the given ISubscriber
to type T and passes it to the other method of the same name.
Since the interfaces method has to be public, technically you could try subscribing an object that is not of type T as long as it is an ISubscriber. Is there a way accomplish this sort of observer pattern without having loose threads or questionable code?