Assignment 3 1) 1.1: Observer Pattern: Goal
Assignment 3 1) 1.1: Observer Pattern: Goal
1) Observer Pattern:
1.1 Goal: Observer Pattern provides an object design such that if state of one of the object
changes then all of its dependents are notified.
Observer Pattern has concept of two types of classes called subject classes and set
of Observer classes. The only thing subject knows about observer is that it
implements interface called Observer interface.
The Subject class Object contains the state and when its state changes, the
observer design allows notification to be send to all the Observer Concrete
classes.
In Observer Pattern, we have one –to- many relationships between a subject object
and set of dependent objects.
Java has inbuilt Observer interface and the Observable class in the java.util
.Observer and java.util.Observable package. The Observable class has methods
Observer interface has update () function which needs to be defined in all the
Observer classes implementing the observer interface.
The figure below shows the high level parallel structure of the Observable Classes
with one Subject class extending it and other side consists of Observer Interface
and many Observable Classes implementing the interface.
1.3 Implementation in Assignment:
The class structure consists of two parallel hierarchies one consist of Subject
Classes (Observable) and other consist of Observer Classes.
The Subject Class consists of the definitions of the Java Public, Private, Protected,
Package, Static and Non Static functions.
The logic implemented is such that whenever we call any function from Main then
using Reflection Java Concept we calculate the access modifier of the called
function at run time and then call setcounter() function defined in subject class to
change the state of the object by passing calculated access modifier as parameter
to it. The setcounter() function will call setChanged() and notifyObservers()
method of the Observable class for notification.
The notifyObservers() method will automatically call or notify update function of
all the registered Observers. The Observers are being registered by using the
addObserver() method of the Observable class.
The figure below shows the Class structure implemented for the assignment to
have more clarity on this.
Summary: The implementation is done in such a way that whenever function is called from
main program then the state of the subject object is changed according to the access modifier of
the called function. Once the state of the object is changed then all the observable classes are
notified the change using notifyObserver() and setchanged() function.