/**
 * {@link <a href=
 * "https://[Log in to view URL]"
 * target= "_blank"></a>}
 * 
 * @author itammb ( Italia Massimiliano Buscati )
 * @version JDK 1.15
 *
 */
class Main {
	interface State {
		void toDo(TrafficLightContext context);
	}

	public static class RedLightState implements State {
		@Override
		public void toDo(TrafficLightContext context) {
			System.out.println("Red Light: Cars must stop.");
			context.setState(new GreenLightState()); // Transizione da Rosso a Verde
		}
	}

	public static class GreenLightState implements State {
		@Override
		public void toDo(TrafficLightContext context) {
			System.out.println("Green Light: Cars can go.");
			context.setState(new YellowLightState()); // Transizione da Verde a Giallo
		}
	}

	public static class YellowLightState implements State {
		@Override
		public void toDo(TrafficLightContext context) {
			System.out.println("Yellow Light: Cars must leave the road clear.");
			context.setState(new RedLightState()); // Transizione da Giallo a Rosso
		}
	}

	public static class TrafficLightContext {
		private State currentState;

		public TrafficLightContext() {
			currentState = new RedLightState(); // Default stato
		}

		public void setState(State state) {
			this.currentState = state; // esegue una transizione
		}

		public void changeLight() {
			currentState.toDo(this); // esegue la logica di uno stato
		}
	}

	public static void main(String args[]) {
		// Unit test - uso del design pattern: state

		TrafficLightContext trafficLight = new TrafficLightContext();

		for (int i = 0; i < 6; i++) {
			trafficLight.changeLight();
			System.out.println();
		}
	}
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: