Java Reference
In-Depth Information
JekyllAndHyde man = new JekyllAndHyde();
// Create Dr. Jekyll
Observer[] crowd = {
new Person("Officer","What's all this then?"),
new Person("Eileen Backwards", "Oh, no, it's horrible Đ those
teeth!"),
new Person("Phil McCavity", "I'm your local dentist Đ here's my
card."),
new Person("Slim Sagebrush", "What in tarnation's goin' on
here?"),
new Person("Freaky Weirdo", "Real cool, man. Where can I get
that stuff?")
};
// Add the observers
for(Observer observer : crowd) {
man.addObserver(observer);
}
man.drinkPotion();
// Dr. Jekyll drinks
up
}
}
Directory "Horrific"
If you compile and run this, you should get the following output:
It's Mr.Hyde
Freaky Weirdo: Real cool, man. Where can I get that stuff?
It's Mr.Hyde
Slim Sagebrush: What in tarnation's goin' on here?
It's Mr.Hyde
Phil McCavity: I'm your local dentist - here's my card.
It's Mr.Hyde
Eileen Backwards: Oh, no, it's horrible - those teeth!
It's Mr.Hyde
Officer: What's all this then?
How It Works
JekyllAndHyde
is a very simple class with just two methods. The
drinkPotion()
method encourages
Dr. Jekyll to do his stuff and change into Mr. Hyde, and the
getName()
method enables anyone who is
interested to find out who he now is. The class extends the
Observable
class, so you can add observers
for a
JekyllAndHyde
object.
The revamped
Person
class implements the
Observer
interface, so an object of this class can observe
an
Observable
object. When notified of a change in the object being observed, the
update()
method is
called. Here, it just outputs who the person is and what he or she says.
In the
Horrific
class, after defining Dr. Jekyll in the variable
man
, you create an array,
crowd
, of type
Observer[]
to hold the observers — which are of type
Person
, of course. You can use an array of type
Observer[]
because the
Person
class implements the
Observer
interface. You pass two arguments to