2

I try to practice with the design patterns and explore one of the possible implementations of the Observer Design Pattern in Java. I paid attention, that in this example the object is defined with the interface type and not the class one:

//user-made observer interface
public interface Observer {…}

//observer class to watch after subject objects
public class MyTopicSubscriber implements Observer {…}

//subject class to notify observer of any updates
public class MyTopicPublisher implements Subject {
     private List<Observer> observers;
}

As you can see, the list observers is a type of Observer, which is an interface. Why decided a programmer, in this case, to use the interface as a type for the list of objects and not the class name MyTopicSubscriber?

The full code example published above:
http://www.journaldev.com/1739/observer-design-pattern-in-java-example-tutorial

Update to moderators:
In this question, I don't ask what exactly the interface is, but why it worths to use the interface as a type of collection's objects. Thus, my question can't be considered as a possible duplicate of the proposed question, which deals with basic explanation of what interfaces in programming are, my question is more narrow and specific.

Thanks.

Mike
  • 135

1 Answers1

3

That's exactly what interfaces are for. The programmer doesn't care what types of objects might be in the list, as long as they provide the method calls expected of any Observer. This way, your list can contain instances of MyTopicSubscriber, MyFileSystemChangeSubscriber, MyMailboxSubscriber, etc. (these are fictitious titles, of course).

By using interfaces in your design, you allow yourself more flexibility in your model, because you now have multiple types of objects being observed, with a simple Observable interface. In a purely inheritance-based design, everything Observable would have to be derived from a single class, even classes that have nothing in common with each other, except that you want to Observe them.

This kind of interface-driven design lends itself very nicely to unit testing, as you can now mock-up any object and insert it into your list to generate the types of behaviors you want to test. As long as it's Observable, and provides the methods expected of any Observable, your code won't care that it's a specialized test object, rather than a regular object from your application.

Kent A.
  • 880