Java Reference
In-Depth Information
package com.oozinoz.carousel;
public class Door_2 extends Observable
{
// ... (DoorState variables)
public void click()
{
state.click();
}
public void complete()
{
state.complete();
}
protected void setState(DoorState state)
{
this.state = state;
setChanged();
notifyObservers();
}
public String status()
{
return state.status();
}
public void timeout()
{
state.timeout();
}
}
The click() , complete() , status() , and timeout() methods show the pure
polymorphism of this approach. Each of these methods is still a kind of switch. In each case,
the operation is fixed, but the class of the receiver—the class of state —varies. The rule of
polymorphism is that the method that executes depends on the operation signature and
the class of the receiver. What happens when you call click() ? The answer depends on
the door's state. The code still effectively performs a switch, but by relying on polymorphism,
the code is simpler than before.
The setState() method in the Door_2 class is now used by subclasses of DoorState .
These subclasses closely resemble their counterparts in the state machine in Figure 22.1. For
example, the code for DoorOpen handles calls to click() and timeout() , the two
transitions from the Open state in the state machine:
package com.oozinoz.carousel;
public class DoorOpen extends DoorState
{
public DoorOpen(Door_2 door)
{
super(door);
}
Search WWH ::




Custom Search