1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
package com.geekcap.designpatterns.observer;
public interface TrafficLightObserver {
public void greenLight();
public void yellowLight();
public void redLight();
}
package com.geekcap.designpatterns.observer;
public class Car implements TrafficLightObserver {
private String name;
public Car( String name ) {
this.name = name;
}
public void greenLight() {
System.out.println( name + ": green light = go" );
}
public void yellowLight() {
System.out.println( name + ": yellow light = slow down" );
}
public void redLight() {
System.out.println( name + ": red light = stop" );
}
}
package com.geekcap.designpatterns.observer;
import java.util.Set;
import java.util.HashSet;
public class TrafficLight implements Runnable {
private Set<TrafficLightObserver> observers = new HashSet<TrafficLightObserver>();
private enum STATE { GREEN, YELLOW, RED };
private boolean running = false;
private Thread thread = new Thread( this );
public void run() {
// Initialize the state of the light
STATE state = STATE.GREEN;
// Initialize the running state
running = true;
while( running ) {
if( state == STATE.GREEN ) {
fireGreenLight();
state = STATE.YELLOW;
}
else if( state == STATE.YELLOW ) {
fireYellowLight();
state = STATE.RED;
}
else {
fireRedLight();
state = STATE.GREEN;
}
try {
Thread.sleep( 2000 );
}
catch( Exception e ) {
}
}
}
public void start() {
thread.start();
}
public void stop() {
running = false;
}
public void addTrafficLightObserver( TrafficLightObserver observer ) {
observers.add( observer );
}
public void removeTrafficLightObserver( TrafficLightObserver observer ) {
observers.remove( observer );
}
private void fireRedLight() {
for( TrafficLightObserver observer : observers ) {
observer.redLight();
}
}
private void fireGreenLight() {
for( TrafficLightObserver observer : observers ) {
observer.greenLight();
}
}
private void fireYellowLight() {
for( TrafficLightObserver observer : observers ) {
observer.yellowLight();
}
}
public static void main( String[] args ) {
Car porsche = new Car( "Porsche" );
Car civic = new Car( "Civic" );
TrafficLight light = new TrafficLight();
light.addTrafficLightObserver( porsche );
light.addTrafficLightObserver( civic );
light.start();
try {
Thread.sleep( 20000 );
}
catch( Exception e ) {
}
light.stop();
}
} |
Partager