상태를 객체로 나타내기
Intent
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.
Implementation

Applicablity
Code Examples
package oodesign.design.behavioral.state; public class Light { protected LightState onState = new OnState(); protected LightState offState = new OffState(); protected LightState lightState; public Light() { this.lightState = new OffState(); } public void on(){ lightState.on(); } public void off(){ lightState.off(); } interface LightState { void on(); void off(); } class OnState implements LightState{ @Override public void on() { System.out.println("nothing"); } @Override public void off() { System.out.println("on -> off"); lightState = offState; } } class OffState implements LightState{ @Override public void on() { System.out.println("off -> on"); lightState = onState; } @Override public void off() { System.out.println("Nothing"); } } }
package oodesign.design.behavioral.state; public class Main { public static void main(String[] args) { Light light = new Light(); light.off(); light.off(); light.off(); light.on(); light.on(); light.on(); light.off(); } }
Nothing Nothing Nothing off -> on nothing nothing on -> off Process finished with exit code 0
Note
- 상태 패턴은 전략 패턴과 UML이 동일함

- Intent 가 다름
- 전략패턴의 execute - 알고리즘의 실행
- 전략패턴의 action - 상태의 변경