


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



public class Door_1 extends Observable { public static final int CLOSED = -1; public static final int CLOSING = -4; public static final int OPEN = -3; public static final int OPENING = -2; private int state = CLOSED; // default public static final int STAYOPEN = -5; // Return a textual description of the door's state. public String status() { switch (state) { case OPENING: return "Opening"; case OPEN: return "Open"; case CLOSING: return "Closing"; case STAYOPEN: return "StayOpen"; default: return "Closed"; }
// The carousel user has clicked the carousel button. This "one touch" button elicits // different behaviors, depending on the state of the door. public void click() { } // This is a notification from the mechanical carousel that the door // finished opening or shutting. public void complete() { } public void testState() { Door_1 d = new Door_1(); assertEquals("Closed", d.status()); d.click(); assertEquals("Opening", d.status()); // Click wjil opening to see d.click(); assertEquals("Closing", d.status()); d.click(); assertEquals("Opening", d.status()); d.complete(); // let the 2 second delay pass assertEquals("Open", d.status()); d.click(); assertEquals("StayOpen", d.status()); d.click(); assertEquals("Closing", d.status()); // Open while closing d.click(); assertEquals("Opening", d.status()); d.click(); assertEquals("Closing", d.status()); d.complete(); assertEquals("Closed", d.status());
// Update the simulated door. private void heartbeat() { if (door.status() == door.OPENING) { incrementPercentClosed(-.04); if (percentClosed <= 0.01) { door.setState(door.OPEN); timeoutTimer().start(); } } else if (door.status() == door.CLOSING) { incrementPercentClosed(.04); if (percentClosed >= 0.99) door.setState(door.CLOSED); } } // This timer makes the carousel seem alive. private Timer heartbeatTimer() { if (heartbeatTimer == null) heartbeatTimer = new Timer(100, this); return heartbeatTimer; } private void incrementPercentClosed(double inc) { percentClosed += inc; percentClosed = Math.min(1.0, percentClosed); percentClosed = Math.max(0.0, percentClosed); if (percentClosed >= 0.99) door.setState(door.CLOSED); else if (percentClosed <= 0.01) door.setState(door.OPEN); setChanged(); notifyObservers(); } // Start the timer that makes a carousel object monitor the state of its door. public void start() { heartbeatTimer().start(); } // Closes automatically in 2 seconds private void timeout() { door.setState(door.CLOSING); setChanged(); notifyObservers(); } private Timer timeoutTimer() { if (timeoutTimer == null) { timeoutTimer = new Timer(2000, this); timeoutTimer.setRepeats(false); } return timeoutTimer; } public String status() { // Return a textual description of the door's state String s = "" + door.status().getClass(); return s.substring(s.lastIndexOf('.') + 1); }