Design patterns

patterns20StatePattern

Path
pkg8patterns/patterns20StatePattern.java
Package
pkg8patterns
Study order
20
Run
Single-file source launch
Command
java pkg8patterns/patterns20StatePattern.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg8patterns/patterns20StatePattern.java
1package pkg8patterns;2 3/*4 * State (Behavioral)5 * ------------------6 * INTENT: allow an object to alter its behavior when its internal state changes;7 *         the object appears to change its class.8 * UML: Context --> State ; concrete states implement transitions.9 * PROS: removes large conditionals; each state is isolated.10 * CONS: more classes; transitions spread across states.11 * REAL-WORLD: TCP connections, vending machines, workflow/order status, UI modes.12 */13public class patterns20StatePattern {14 15    interface State { State next(); String name(); }16 17    // A simple traffic light: GREEN -> YELLOW -> RED -> GREEN18    static class Green implements State {19        public State next() { return new Yellow(); }20        public String name() { return "GREEN (go)"; }21    }22    static class Yellow implements State {23        public State next() { return new Red(); }24        public String name() { return "YELLOW (slow)"; }25    }26    static class Red implements State {27        public State next() { return new Green(); }28        public String name() { return "RED (stop)"; }29    }30 31    static class TrafficLight {32        private State state = new Green();33        void change() { state = state.next(); }34        String status() { return state.name(); }35    }36 37    public static void main(String[] args) {38        TrafficLight light = new TrafficLight();39        for (int i = 0; i < 5; i++) {40            System.out.println(light.status());41            light.change();42        }43    }44}