Java Reference
In-Depth Information
}
Our subject class is the Moon , which keeps a list of LandingObserver instances, notifies
them of landings, and can add new LandingObserver instances to spy on the Moon object
( Example 8-16 ) .
Example 8-16. Our Moon domain class—not as pretty as the real thing
public
public class
class Moon
Moon {
private
private final
final List < LandingObserver > observers = new
new ArrayList <>();
public
public void
void land ( String name ) {
for
for ( LandingObserver observer : observers ) {
observer . observeLanding ( name );
}
}
public
public void
void startSpying ( LandingObserver observer ) {
observers . add ( observer );
}
}
We have two concrete implementations of the LandingObserver class that represent the ali-
ens' ( Example 8-17 ) and NASA's views ( Example 8-18 ) of the landing event. As mentioned
earlier, they both have different interpretations of what this situation brings them.
Example 8-17. The aliens can observe people landing on the moon
public
public class
class Aliens
Aliens implements
implements LandingObserver {
@Override
public
public void
void observeLanding ( String name ) {
iif ( name . contains ( "Apollo" )) {
System . out . println ( "They're distracted, lets invade earth!" );
}
}
}
Example 8-18. NASA can also observe people landing on the moon
public
public class
class Nasa
Nasa implements
implements LandingObserver {
@Override
public
public void
void observeLanding ( String name ) {
Search WWH ::




Custom Search