HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
객체 지향 프로그래밍
객체 지향 프로그래밍
/
디자인 패턴
디자인 패턴
/
🇺🇸
State Pattern
🇺🇸

State Pattern

💡
상태를 객체로 나타내기

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

notion image
 

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이 동일함
notion image
  • Intent 가 다름
    • 전략패턴의 execute - 알고리즘의 실행
    • 전략패턴의 action - 상태의 변경