# Computer Science Design Patterns/Observer
## Scope

Object

## Purpose

Behavioral

## Intent

Define a one-to-many dependency between objects so that when one object changes state (the Subject), all its dependents (the Observers) are notified and updated automatically.

## Applicability

* when an abstraction has two aspects, one dependent on the other
* when a change to one object requires changing others, and you don't know how many objects need to be changed
* when an object should notify other objects without making assumptions about who these objects are

## Consequences

* + modularity: subject and observers may vary independently
* + extensibility: can define and add any number of observers
* + customizability: different observers provide different views of subject
* - unexpected updates: observers don't know about each other
* - update overhead: might need hints

## Implementation

* subject-observer mapping
* dangling references
* avoiding observer-specific update protocols: the push and pull models
* registering modifications of interest explicitly

## Related pattern

* Singleton, is used to make observable object unique and accessible globally.
* Mediator, is used to encapsulate updated objects

## Description
### Problem

    In one place or many places in the application we need to be aware about a system event or an application state change. We'd like to have a standard way of subscribing to listening for system events and a standard way of notifying the interested parties. The notification should be automated after an interested party subscribed to the system event or application state change. There should be a way to unsubscribe, too.

### Forces

    Observers and observables probably should be represented by objects. The observer objects will be notified by the observable objects.

### Solution

    After subscribing the listening objects will be notified by a way of method call.

### Loose coupling

    When two objects are loosely coupled, they can interact, but they have very little knowledge of each other. Strive for loosely coupled designs between objects that interact.
* The only thing that Subject knows about an observer is that it implements a certain interface
* We can add new observers at any time
* We never need to modify the subject to add new types of observers
* We can reuse subjects or observers independently of each other
* Changes to either the subject or an observer will not affect the other

## Examples

The Observer pattern is used extensively in Java. E.g. in the following piece of code
* button is the Subject
* MyListener is the Observer
* actionPerformed is the equivalent to update
Another example is the PropertyChangeSupport. The Component class uses a PropertyChangeSupport object to let interested observers register for notification of changes in the properties of labels, panels, and other GUI components.
Can you find the Subject, Observer and update in the above class diagram?
* Component is the Subject
* PropertyChangeListener is the Observer
* propertyChange is the equivalent to update

## Cost

This pattern can be tricky if you do not beware. Beware the data representing the state changes of the subject can evolve without changing the interfaces. If you only transmit a string, the pattern could become very expensive if at least one new observer needs also a state code. You should use a mediator unless you know the implementation of the subject state will never change.

### Creation

This pattern has a cost to create.

### Maintenance

This pattern can be expensive to maintain.

### Removal

This pattern has a cost to remove too.

## Advises

* Put the subject and observer term in the name of the subject and the observer classes to indicate the use of the pattern to the other developers.
* To improve performances, you can only send to the observers the difference of states instead of the new state. The observers can only update following the changed part of the subject instead of all the state of the subject.

## Traditional Method

C# and the other .NET Framework languages do not typically require a full implementation of the Observer pattern using interfaces and concrete objects. Here is an example of using them, however.

## Using Events

The alternative to using concrete and abstract observers and publishers in C# and other .NET Framework languages, such as Visual Basic, is to use events. The event model is supported via delegates that define the method signature that should be used to capture events. Consequently, delegates provide the mediation otherwise provided by the abstract observer, the methods themselves provide the concrete observer, the concrete subject is the class defining the event, and the subject is the event system built into the base class library. It is the preferred method of accomplishing the Observer pattern in.NET applications.

## Handy implementation

You can implement this pattern in Java like this:

## Built-in support

The Java JDK has several implementations of this pattern: application in Graphical User Interfaces such as in the AWT toolkit, Swing etc. In Swing, whenever a user clicks a button or adjusts a slider, many objects in the application may need to react to the change. Swing refers to interested clients (observers) as "listeners" and lets you register as many listeners as you like to be notified of a component's events.
MVC is more M(VC) in Swing, i.e. View and Controller are tightly coupled; Swing does not divide Views from Controllers. MVC supports n-tier development, i.e. loosely coupled layers (see below) that can change independently and that may even execute on different machines.
There is also a built-in support for the Observer pattern. All one has to do is extend java.util.Observable (the Subject) and tell it when to notify the java.util.Observer s. The API does the rest for you. You may use either push or pull style of updating your observers.
java.util.Observable is a class while java.util.Observer is an interface.
Note that you have to call setChanged so that the Observable code will broadcast the change. The notifyObservers method calls the update method of each registered observer. The update method is a requirement for implementers of the Observer Interface.

### Keyboard handling

Below is an example written in Java that takes keyboard input and treats each input line as an event. The example is built upon the library classes java.util.Observer and java.util.Observable. When a string is supplied from System.in, the method notifyObservers is then called, in order to notify all observers of the event's occurrence, in the form of an invocation of their 'update' methods - in our example, ResponseHandler.update(...).
The file MyApp.java contains a main method that might be used in order to run the code.
The Java implementation of the Observer pattern has pros and cons:
Pros
* It hides many of the details of the Observer pattern
* It can be used both pull and push ways.
Cons
* Because Observable is a class, you have to subclass it; you can’t add on the Observable behavior to an existing class that subclasses another superclass (fails the programming to interfaces principle). If you can’t subclass Observable, then use delegation, i.e. provide your class with an Observable object and have your class forward key method calls to it.
* Because setChanged is protected, you can’t favour composition over inheritance.
class STUDENT
class TEACHER
Class SUBJECT
Application
OUTPUT
First Subject
Second Subject
The observer pattern in Python:
The observer pattern can be implemented more succinctly in Python using function decorators.
In Ruby, use the standard Observable mixin. For documentation and an example, see http://www.ruby-doc.org/stdlib/libdoc/observer/rdoc/index.html