|
| 1 | +public class TrafficLightFSM { |
| 2 | + // State Interface |
| 3 | + interface TrafficLightState { |
| 4 | + void handleEvent(TrafficLightContext context); |
| 5 | + } |
| 6 | + |
| 7 | + // Concrete States |
| 8 | + static class RedLightState implements TrafficLightState { |
| 9 | + @Override |
| 10 | + public void handleEvent(TrafficLightContext context) { |
| 11 | + System.out.println("Red Light: Stop!"); |
| 12 | + context.setState(new GreenLightState()); |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + static class GreenLightState implements TrafficLightState { |
| 17 | + @Override |
| 18 | + public void handleEvent(TrafficLightContext context) { |
| 19 | + System.out.println("Green Light: Go!"); |
| 20 | + context.setState(new YellowLightState()); |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + static class YellowLightState implements TrafficLightState { |
| 25 | + @Override |
| 26 | + public void handleEvent(TrafficLightContext context) { |
| 27 | + System.out.println("Yellow Light: Caution!"); |
| 28 | + context.setState(new RedLightState()); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + // Context Class |
| 33 | + static class TrafficLightContext { |
| 34 | + private TrafficLightState currentState; |
| 35 | + |
| 36 | + public TrafficLightContext(TrafficLightState initialState) { |
| 37 | + this.currentState = initialState; |
| 38 | + } |
| 39 | + |
| 40 | + public void setState(TrafficLightState newState) { |
| 41 | + this.currentState = newState; |
| 42 | + } |
| 43 | + |
| 44 | + public void handleEvent() { |
| 45 | + currentState.handleEvent(this); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + // Main Method |
| 50 | + public static void main(String[] args) { |
| 51 | + // Initialize the traffic light with the Red state |
| 52 | + TrafficLightContext trafficLight = new TrafficLightContext(new RedLightState()); |
| 53 | + |
| 54 | + // Simulate events |
| 55 | + for (int i = 0; i < 6; i++) { |
| 56 | + trafficLight.handleEvent(); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments