Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
PerfectJPattern's componentized version of the Observer Pattern provides the following advantages:
IEventData
subtype.
Type-safety is enforced because Subject instances will only subscribe/attach Observers that
comply with the correct event data type whereas e.g. Sun JDK's Observer implementation relies
on an Object
type-unsafe parameter.
update(...)
method throw an unchecked exception are automatically detached. Not doing so would
put Subject instances at risk of the unexpected behavior coming from faulty Observers.
ObserverProxy
implementation: allows plain POJO types and free
method signatures (currently only one parameter) to be targeted as result of a notification.
This extension removes the otherwise needed dependency from PerfectJPattern allowing to
directly target existing legacy code that does not subtype IObserver
.
AsynchronousSubject
implementation: executes each Observer update(...)
method in a separate thread so that Subject's client is minimally blocked waiting for all Observers to be
notified and handle their update(...)
method, specially when there is a large number of Observer
subscribed. This facility is also recommended because would protect Subject instances and its client from
a possible greedy Observer e.g. an Observer whose update(...)
implementation goes to an infinite
loop. It is highly encouraged to use an Immutable Object type as event data.
Composite
and
SynchronizedProxy
componentized patterns.
SynchronizedProxy
avoids race condition in the
Observer update(...) method.ParameterlessSubject
that provides a parameterless notifyObservers()
convenience method. The Observers are required to subclass the type Observer<NullEventData>.
In this case the update(NullEventData anEventData)
method will always receive the
Singleton instance of NullEventData
see
NullObject Pattern to avoid the
potential risk of NullPointerException
if the Observer implementation tries reading
the event data parameter.
IEventData
are highly (really!) encouraged to be an
Immutable Object type. Making
event data Immutable offers the extra advantage not only of a self-consistent state notifying
Observers but also no risk of race-hazards when Subject notifications are published from
separate threads.