Java Reference
In-Depth Information
Items that can't be switched must nonetheless be in the database, for various purposes (audit-
ing, insurance, etc.). In the method that turns things off, the code is careful to check whether
each object in the database is an instance of the PowerSwitchable interface. If so, the object
is casted to PowerSwitchable so that its powerDown() method can be called. If not, the ob-
ject is skipped, thus preventing any possibility of turning out the emergency lights or shutting
off a machine that is busy running Seti@Home , downloading a big MP3 playlist, or perform-
ing system backups. The following code shows this set of classes in action:
public
public class
class BuildingManagement
BuildingManagement {
Asset things [] = new
new Asset [ 24 ];
int
int numItems = 0 ;
/** Scenario: goodNight() is called from a timer Thread at 2200, or when
* we get the "shutdown" command from the security guard.
*/
public
public void
void goodNight () {
for
for ( int
int i = 0 ; i < things . length ; i ++)
iif ( things [ i ] instanceof
instanceof PowerSwitchable )
(( PowerSwitchable ) things [ i ]). powerDown ();
}
// goodMorning() would be the same, but call each one's powerUp().
/** Add a Asset to this building */
public
public void
void add ( Asset thing ) {
System . out . println ( "Adding " + thing );
things [ numItems ++] = thing ;
}
/** The main program */
public
public static
void main ( String [] av ) {
BuildingManagement b1 = new
static void
new BuildingManagement ();
b1 . add ( new
new RoomLights ( 101 ));
// control lights in room 101
b1 . add ( new
new EmergencyLight ( 101 )); // and emerg. lights.
// add the computer on desk#4 in room 101
b1 . add ( new
new ComputerCPU ( 10104 ));
// and its monitor
b1 . add ( new
new ComputerMonitor ( 10104 ));
// time passes, and the sun sets...
b1 . goodNight ();
Search WWH ::




Custom Search