Skip to content

Latest commit

 

History

History
42 lines (34 loc) · 706 Bytes

readme.md

File metadata and controls

42 lines (34 loc) · 706 Bytes

State pattern

"State is a behavioral design pattern that lets an object alter its behavior when its internal state changes. It appears as if the object changed its class." - source

Class diagram

class-diagram

Example

Main.java:

TrafficLight trafficLight = new TrafficLight();

int count = 0;
while(count < 10) {
    try {
        trafficLight.printState();
        trafficLight.nextState();
        Thread.sleep(1000);
        count++;
    } catch (InterruptedException e) {
        e.printStackTrace();
        break;
    }
}

Output:

RED
YELLOW
GREEN
YELLOW
RED
YELLOW
GREEN
YELLOW
RED
YELLOW