100% found this document useful (1 vote)
689 views9 pages

Observer and Observable An Introduction To The Observer Interface and Observable Class Using The Model/View/Controller Architecture As A Guide

This document provides an introduction to the Observer interface and Observable class in Java and how they can be used to implement the Model-View-Controller (MVC) architecture. It describes the key components of MVC - the model, view, and controller. The Observer interface and Observable class handle notifications when the model changes, allowing views to automatically update. The document gives examples of how to create an observable class that extends Observable and how to create observer classes that implement the Observer interface to receive notifications.

Uploaded by

prasad.dls
Copyright
© Public Domain
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
689 views9 pages

Observer and Observable An Introduction To The Observer Interface and Observable Class Using The Model/View/Controller Architecture As A Guide

This document provides an introduction to the Observer interface and Observable class in Java and how they can be used to implement the Model-View-Controller (MVC) architecture. It describes the key components of MVC - the model, view, and controller. The Observer interface and Observable class handle notifications when the model changes, allowing views to automatically update. The document gives examples of how to create an observable class that extends Observable and how to create observer classes that implement the Observer interface to receive notifications.

Uploaded by

prasad.dls
Copyright
© Public Domain
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 9

Observer and Observable

An introduction to the Observer interface and Observable class using


the Model/View/Controller architecture as a guide

Summary
Here's an introduction to the Observer interface and the
Observable class found in the Java programming language class
library. This article describes both and demonstrates how they
can be used to implement programs based on the
Model/View/Controller architecture introduced and popularized
by the Smalltalk programming language. (2,200 words)

Here's the problem: You're designing a program that will render data
describing a three-dimensional scene in two dimensions. The program must
be modular and must permit multiple, simultaneous views of the same scene.
Each view must be able to display the scene from a different vantage point,
under different lighting conditions. More importantly, if any portion of the
underlying scene changes, the views must update themselves.
None of these requirements presents an insurmountable programming
challenge. If the code that handles each requirement had to be written de
novo, however, it would add significant work to the overall effort. Fortunately,
support for these tasks is already provided by the Java class library in the
form of interface Observer and class Observable. The functionalities of these
two were inspired, in part, by the requirements of the Model/View/Controller
architecture.
The Model/View/Controller architecture
The Model/View/Controller architecture was introduced as part of the
Smalltalk-80 version of the Smalltalk programming language (a popular
object-oriented programming language invented by Alan Kay). The
Model/View/Controller architecture was designed to reduce the programming
effort required to build systems that made use of multiple, synchronized
presentations of the same data. Its central characteristics are that the model,
the controllers, and the views are treated as separate entities, and that
changes made to the model should be reflected automatically in each of the
views.
In addition to the program example described in the opening paragraph
above, the Model/View/Controller architecture may be used for projects such
as the following:

• A graph package that contains simultaneous bar-chart, line-chart, and


pie-chart views of the same data
• A CAD system, in which portions of the design can be viewed at
different magnifications, in different windows, and at different scales

Figure 1 illustrates the Model/View/Controller architecture in its most general


form. There is one model. Multiple controllers manipulate the model; multiple
views display the data in the model, and change as the state of the model
changes.

1
Figure 1: The Model/View/Controller architecture
The Model/View/Controller architecture has several benefits:

• There is a clearly defined separation between components of a


program -- problems in each domain can be solved independently.
• There is a well defined API -- anything that uses the API properly can
replace either the model, the view, or the controller.
• The binding between the model and the view is dynamic -- it occurs at
run time, rather than at compile time.

By incorporating the Model/View/Controller architecture into a design, pieces


of a program can be designed separately (and designed to do their job well)
and then bound together at run time. If a component is later deemed to be
unsuitable, it can be replaced without affecting the other pieces. Contrast
that scenario with the monolithic approach typical of many quick-and-dirty
Java programs. Often a frame contains all of the state, handles all events,
does all of the calculations, and displays the result. Thus, in all but the
simplest of such systems, making changes after the fact is not trivial.
Defining the parts
The model is the object that represents the data in the program. It manages
the data and conducts all transformations on that data. The model has no
specific knowledge of either its controllers or its views -- it contains no
internal references to either. Rather, the system itself takes on the
responsibility of maintaining links between the model and its views and
notifying the views when the model changes.
The view is the object that manages the visual display of the data
represented by the model. It produces the visual representation of the model
object and displays the data to the user. It interacts with the model via a
reference to the model object itself.
The controller is the object that provides the means for user interaction with
the data represented by the model. It provides the means by which changes
are made, either to the information in the model or to the appearance of the
view. It interacts with the model via a reference to the model object itself.
At this point a concrete example might be helpful. Consider as an example
the system described in the introduction.

Figure 2: Three-dimensional visualization system

2
The central piece of the system is the model of the three-dimensional scene.
The model is a mathematical description of the vertices and the faces that
make up the scene. The data describing each vertex or face can be modified
(perhaps as the result of user input or a scene distortion or morphing
algorithm). However, there is no notion of point of view, method of display
(wireframe or solid), perspective, or light source. The model is a pure
representation of the elements that make up the scene.
The portion of the program that transforms the data in the model into a
graphical display is the view. The view embodies the actual display of the
scene. It is the graphical representation of the scene from a particular point
of view, under particular lighting conditions.
The controller knows what can be done to the model, and implements the
user interface that allows that action to be initiated. In this example, a data
entry control panel might allow the user to add, modify, or delete vertices
and faces.
Observer and Observable
The Java programming language provides support for the
Model/View/Controller architecture with two classes:

• Observer -- any object that wishes to be notified when the state of


another object changes
• Observable -- any object whose state may be of interest, and in whom
another object may register an interest

These two classes can be used to implement much more than just the
Model/View/Controller architecture. They are suitable for any system wherein
objects need to be automatically notified of changes that occur in other
objects.
Typically, the model is a subtype of Observable and the view is a subtype of
observer. These two classes handle the automatic notification function of the
Model/View/Controller architecture. They provide the mechanism by which
the views can be automatically notified of changes in the model. Object
references to the model in both the controller and the view allow access to
data in the model.
Observer and Observable functions
The following are code listings for observer and observable functions:
Observer
public void update(Observable obs, Object obj)
Called when a change has occurred in the state of the observable.
Observable
public void addObserver(Observer obs)
Adds an observer to the internal list of observers.
public void deleteObserver(Observer obs)
Deletes an observer from the internal list of observers.
public void deleteObservers()
Deletes all observers from the internal list of observers.
public int countObservers()
Returns the number of observers in the internal list of observers.
protected void setChanged()
Sets the internal flag that indicates this observable has changed state.
protected void clearChanged()
Clears the internal flag that indicates this observable has changed
state.
public boolean hasChanged()
Returns the boolean value true if this observable has changed state.
public void notifyObservers()
3
Checks the internal flag to see if the observable has changed state and
notifies all observers.
public void notifyObservers(Object obj)
Checks the internal flag to see if the observable has changed state and
notifies all observers. Passes the object specified in the parameter list
to thenotify() method of the observer.
How to use interface Observer and class Observable
The following section describes in detail how to create a new observable class
and a new observer class, and how to tie the two together.
Extend an observable
A new class of observable objects is created by extending class Observable.
Because class Observable already implements all of the methods necessary
to provide the observer/observable behavior, the derived class need only
provide some mechanism for adjusting and accessing the internal state of the
observable object.
In the class ObservableValue listing below, the internal state of the model is
captured by the integer n. This value is accessed (and, more importantly,
modified) only through public accessors. If the value is changed, the
observable object invokes its own setChanged() method to indicate that the
state of the model has changed. It then invokes its
own notifyObservers() method in order to update all of the registered
observers.
import java.util.Observable;

public class ObservableValue extends Observable


{
private int n = 0;

public ObservableValue(int n)
{
this.n = n;
}

public void setValue(int n)


{
this.n = n;

setChanged();
notifyObservers();
}

public int getValue()


{
return n;
}
}

Implement an observer
A new class of objects that observe the changes in state of another object is
created by implementing the Observer interface. The Observer interface
requires that an update() method be provided in the new class.
The update() method is called whenever the observable changes state and
announces this fact by calling its notifyObservers() method. The observer
should then interrogate the observable object to determine its new state,
and, in the case of the Model/View/Controller architecture, adjust its view
appropriately.
4
In the following class TextObserver listing, the notify() method first checks to
ensure that the observable that has announced an update is the observable
that this observer is observing. If it is, it then reads the observable's state,
and prints the new value.
import java.util.Observer;
import java.util.Observable;

public class TextObserver implements Observer


{
private ObservableValue ov = null;

public TextObserver(ObservableValue ov)


{
this.ov = ov;
}

public void update(Observable obs, Object obj)


{
if (obs == ov)
{
System.out.println(ov.getValue());
}
}
}

Tie the two together


A program notifies an observable object that an observer wishes to be
notified about changes in its state by calling the observable
object's addObserver()method. The addObserver() method adds the observer
to the internal list of observers that should be notified if the state of the
observable changes.
The example below, showing class Main, demonstrates how to use
the addObserver() method to add an instance of the TextObserver class (see
the TextObserver listing above) to the observable list maintained by the
ObservableValue class (see the ObservableValue listing above).
public class Main
{
public Main()
{
ObservableValue ov = new ObservableValue(0);
TextObserver to = new TextObserver(ov);

ov.addObserver(to);
}

public static void main(String [] args)


{
Main m = new Main();
}
}

How it all works together


The following sequence of events describes how the interaction between an
observable and an observer typically occurs within a program.

5
1. First the user manipulates a user interface component representing a
controller. The controller makes a change to the model via a public
accessor method -- which is setValue() in the example above.
2. The public accessor method modifies the private data, adjusts the
internal state of the model, and calls its setChanged() method to
indicate that its state has changed. It then calls notifyObservers() to
notify the observers that it has changed. The call
to notifyObservers() could also be performed elsewhere, such as in an
update loop running in another thread.
3. The update() methods on each of the observers are called, indicating
that a change in state has occurred. The observers access the model's
data via the model's public accessor methods and update their
respective views.

A demonstration
The example in Figure 3 demonstrates how observables and observers
typically work together in the Model/View/Controller architecture.

Figure 3: A better example


Like the model in the class ObservableValue listing shown previously, the
model in this example is very simple. Its internal state consists of a single
integer value. The state is manipulated exclusively via accessor methods like
those in class ObservableValue. The code for the model is found here.
Initially, a simple text view/controller class was written. The class combines
the features of both a view (it textually displays the value of the current state
of the model) and a controller (it allows the user to enter a new value for the
state of the model). The code is found here. Instances of this view can be
created by pressing the upper button in Figure 3.
By designing the system using the Model/View/Controller architecture (rather
than embedding the code for the model, the view, and the text controller in
one monolithic class), the system is easily redesigned to handle another view
and another controller. In this case, a slider view/controller class was written.
The position of the slider represents the value of the current state of the
model and can be adjusted by the user to set a new value for the state of the
model. The code is found here. Instances of this view object can be created
by pressing the bottom button in Figure 3.
Conclusion
Coming up next month is an introductory "how-to" on graphics that should
prepare the way for future columns on advanced topics such as animation
and custom components. As always, I am interested in hearing from you.
Send me mail if you have a suggestion for a future column or a question you
would like addressed.

observer-pattern-in-java
Continuing to update knowledge about design patterns today we will see
widely used and popular Observer Pattern.
Wikipedia Says:
Observer Pattern is used to observe the state of an object in a program. It
relates to the principle of Implicit Invocation.
Implicit invocation: System may be structured around event handling using
a form of callback.It closely relates to inversion of control what is also known
as Hollywood Principle(Donot call us we will call you) which means instead of
programmer specifying function calls i.e a series of events to happen,
6
they would rather register desired responses to particular happenings.
Hence one or more Objects(Observers or listeners) are registered with
Subject to raise an event.
Responsibilities of Subject:
a) Subject can add, remove and notify observers .All observers should
register with Subject by means of some utilityMethod say addObserver().
Similarly observers may be removed to means of any utility method like
removeObserver().
b) An Observer may be notified of changes by notify() and notifyAll() which
notifies all observers.
Responsibilities of Observer:
a) All subclasses of class Observer(Ideally Observer class may be an abstract
class so that subclasses can define the implementation of notify() method.
As you have observed Observer Pattern defines one-to-many relationship
between subject-observers.
One Advantage of Observer Pattern is it decouples the observer from the
subject.
Consequences Of Observer Pattern
- Unknown Updates: Observers has no knowledge about each other and
update dependency can be hard to track down.
Observer Pattern In Java:
Java Provides builtin classes Observer and Observable to achieve this
functionality.AWT/Swing event model uses ObserverPattern to large extend
especially in event handling.
Below example shows one usage of Observer pattern.For Example we may
need to send all Admin Previlage Users Profiles to our CEO in our
organisation.

class NotifyAdminUsers extends Observable {

void notifyAdminUsers(EmployeeObserver employeeObserver) {


Vector<EmployeeTO> v=employeeObserver.getEmployeeList();

addObserver(employeeObserver);

for (EmployeeTO employeeTO : v) {


if(employeeTO.isAdmin) {
setChanged();
notifyObservers(employeeTO);
}
}
}

class EmployeeTO implements Serializable {

String name;
7
//.....
boolean isAdmin;

public boolean isAdmin() {


return isAdmin;
}
public void setAdmin(boolean isAdmin) {
this.isAdmin = isAdmin;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

class EmployeeObserver implements Observer {

public Vector<EmployeeTO> employeeList;

EmployeeObserver() {
employeeList=new Vector<EmployeeTO>();
}

public void addEmployee(EmployeeTO employee) {


this.employeeList.add(employee);
}

public Vector<EmployeeTO> getEmployeeList() {


return employeeList;
}

public void setEmployeeList(Vector<EmployeeTO> employeeList) {


this.employeeList = employeeList;
}

public void update(Observable observable,Object obj) {


// Some Condition dependent on Application.
if(observable instanceof NotifyAdminUsers) {
if(obj instanceof EmployeeTO) {
System.out.println("Emp Notified:" + ((EmployeeTO)obj).getName());
// send mail to our company CEO. oooh!
// Do stuff which is applicable.
}
}
}
8
}

public class ObserverPattern {


public static void main(String[] args) {

// Initialize Both Observable and Observer.


NotifyAdminUsers adminUsers=new NotifyAdminUsers();
EmployeeObserver employeeObserver=new EmployeeObserver();

for(int i=1;i<=5;i++) {
EmployeeTO employeeTO=new EmployeeTO();
employeeTO.setName("Name:" + i);
employeeTO.setAdmin((i%2)==0);
employeeObserver.addEmployee(employeeTO);
}
// Notify All Admin Users.
adminUsers.notifyAdminUsers(employeeObserver);
}
}

You might also like