Java Reference
In-Depth Information
Notice that you can register many observers with the
NewsAgency
and receive updates. Perhaps a
TVChannel
observer or an
InternetNewsChannel
observer can register to receive updates from
the
NewsAgency
. In addition, you can have other
y Publishers
(or any other type of object that
implements
Observable
) issue updates to any observer that wants to register itself to receive news.
These observers can check the type of the
Observable
and process the update according to its source.
One signii cant drawback of implementing the observer pattern in this way is that you have to extend
the
Observable
class. This forces the use of a class hierarchy that might not be desirable. Because you
cannot extend more than one class in the single‐inheritance world of Java, this way of implementing
the observer pattern restricts the inheritance design. You can't add the
Observable
behavior to an
existing class that already extends another superclass, thus restricting its reuse potential.
But don't despair. You can also implement the observer pattern by “hand,” without using the
internal
Observer
and
Observable
interfaces, by following the given class diagram. However,
because this topic is focused on Java EE, this implementation is left for you to play with.
IMPLEMENTING THE OBSERVER PATTERN IN JAVA EE
Although Java had built‐in support for the observer pattern from inception, Java EE offers an easier
implementation via the
@Observes
annotation and
javax.enterprise.event.Event<T>
interface. Any
method annotated with
@Observes
listens for events of a certain type. When it “hears” such an event,
the parameter of the observer method receives an instance of the type and then executes the method.
The
@Observes
annotation lets any method listen for any event to be i red with the marked object
type. Listing 11‐4 is a simple example of a bean that i res an event of type
String
and another bean
that listens for events of that type from our bean.
LISTING 11‐4:
The observable service bean
package com.devchronicles.observer;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.event.Event;
import javax.inject.Inject;
@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class EventService {
@Inject
private String message;
@Inject
Event<String> event;
public void startService(){
event.fire("Starting service " + message);
}
}