package StatePatternDemoOne; public interface State { public void doAction(); }
package StatePatternDemoOne; public class TVStartState implements State { @Override public void doAction() { System.out.println("TV is turned ON"); } }
package StatePatternDemoOne; public class TVStopState implements State { @Override public void doAction() { System.out.println("TV is turned OFF"); } }
package StatePatternDemoOne; public class TVContextClass implements State { private State tvState; public void setState(State state) { this.tvState = state; } public State getState() { return this.tvState; } @Override public void doAction() { this.tvState.doAction(); } }
Driver - TVRemote:
package StatePatternDemoOne; public class TVRemote { public static void main(String[] args) { TVContextClass context = new TVContextClass(); State tvStartState = new TVStartState(); State tvStopState = new TVStopState(); context.setState(tvStartState); context.doAction(); context.setState(tvStopState); context.doAction(); } }