Search code examples
javainterfaceobserver-pattern

How Interfaces Perform Actions


Right now I came across the Observer/Observable pattern where I have my Observable notify all of my Observers. The Observers all implement the interface Observer while the Observable extends Observable. I guess I'm trying to fill a knowledge gap that I have for interfaces. I understand the point of abstract classes and how they work, but interfaces have been tricky. For interfaces, I understand that they act as templates and if you implement one then you need to add all methods from the interface. I thought that this was purely for organizational help in your project.

With this Observer/Observable case though, I don't understand how the update() function is being called in the Objects that implement Observer. The only link to the Observable is that you have to call addObserver() to add the Observer which then stores it in a list with the other Observers added. But after that, how does update() get called on each Observer? Does the Observable just go one by one through the list of Observers and call observer.update() once I call setChanged() and then notifyObservers()? This would make sense, but the implementation is more hidden than I thought.

I put this in the context of the Observer pattern, but it goes for anything really. I've noticed that nearly all event based things use interfaces. Is this because it is guaranteed that the Object will have the function that is then called?


Solution

  • Yes. An interface defines a contract. All classes implementing the interface have to obey this contract. When you want to observe an Observable, all you need to do is to obey the contract of an Observer: implement the Observer interface and thus have an update method which can be called by the Observable.

    The concrete type of the Observer doesn't matter to the Observable. Using an interface is very handy, because it allows any kind of object to observe an Observable, as long as it implements the Observer interface. You don't need to have any specific concrete type, or to extend any particular class to observe an Observable.