0

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?

Jedi_Maseter_Sam
  • 753
  • 4
  • 24

2 Answers2

1

Check the instance type when adding an observer

// in you observer class
public void subscribe(ISubscriber s) {
  if( s instanceof YouTubeSubscriber) {
       System.out.println("Subscriber added");
  } else {
    // ignore the subscriber
    System.out.println("Subscriber rejected");
  }
}
Robert I
  • 1,509
  • 2
  • 11
  • 18
0

Good idea! This pattern's so useful, IObservable is a built-in .Net interface. MSDN documentation provides more details. Your subscriber idea is represented by IObserver, also documented on MSDN.

The IObserver and IObservable interfaces provide a generalized mechanism for push-based notification, also known as the observer design pattern. The IObservable interface represents the class that sends notifications (the provider); the IObserver interface represents the class that receives them (the observer). T represents the class that provides the notification information [the data transfer object]...

Khelvaster
  • 852
  • 1
  • 6
  • 18