Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
In Java, concrete observers are often created using anonymous constructors as in
ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent ev) { // response to a button click, for example } };
The advantage of this syntax is that it allows code in the
actionPerformed()
method to access data from the object in
which it is embedded.
Many object-oriented languages provide similar functionality though the
syntax varies quite a bit.
Although this can be considered to be a violation of encapsulation, it
often improves encapsulation since the class that contains the anonymous
constructor does not have to declare public methods for the access.