상태 패턴

소프트웨어 디자인 패턴

상태 패턴(state pattern)은 객체 지향 방식으로 상태 기계를 구현하는 행위 소프트웨어 디자인 패턴이다. 상태 패턴을 이용하면 상태 패턴 인터페이스의 파생 클래스로서 각각의 상태를 구현함으로써, 또 패턴의 슈퍼클래스에 의해 정의되는 메소드를 호출하여 상태 변화를 구현함으로써 상태 기계를 구현한다.

상태 패턴은 패턴의 인터페이스에 정의된 메소드들의 호출을 통해 현재의 전략을 전환할 수 있는 전략 패턴으로 해석할 수 있다.

개요 편집

상태[1] 디자인 패턴은 유연하고 재사용 가능한 객체 지향 소프트웨어를 설계하기 위해 반복되는 디자인 문제를 해결하는 방법, 즉 객체는 구현, 변경, 테스트, 재사용이 쉬워야 한다는 것을 기술하는, 잘 알려진 23가지 GoF 디자인 패턴들 중 하나이다.

구조 편집

UML 클래스 및 시퀀스 다이어그램 편집

 
상태 디자인 패턴을 위한 샘플 UML 클래스와 시퀀스 다이어그램.[2]

클래스 다이어그램 편집

 
UML의 상태[1][3]
 
LePUS3이ㅡ 상태[3][4]

편집

자바 편집

interface Statelike {
    void writeName(StateContext context, String name);
}

class StateLowerCase implements Statelike {
    @Override
    public void writeName(final StateContext context, final String name) {
        System.out.println(name.toLowerCase());
        context.setState(new StateMultipleUpperCase());
    }
}

class StateMultipleUpperCase implements Statelike {
    /** Counter local to this state */
    private int count = 0;

    @Override
    public void writeName(final StateContext context, final String name) {
        System.out.println(name.toUpperCase());
        /* Change state after StateMultipleUpperCase's writeName() gets invoked twice */
        if(++count > 1) {
            context.setState(new StateLowerCase());
        }
    }
}
class StateContext {
    private Statelike myState;
    StateContext() {
        setState(new StateLowerCase());
    }

    /**
     * Setter method for the state.
     * Normally only called by classes implementing the State interface.
     * @param newState the new state of this context
     */
    void setState(final Statelike newState) {
        myState = newState;
    }

    public void writeName(final String name) {
        myState.writeName(this, name);
    }
}

아래는 사용법이다:

public class DemoOfClientState {
    public static void main(String[] args) {
        final StateContext sc = new StateContext();

        sc.writeName("Monday");
        sc.writeName("Tuesday");
        sc.writeName("Wednesday");
        sc.writeName("Thursday");
        sc.writeName("Friday");
        sc.writeName("Saturday");
        sc.writeName("Sunday");
    }
}

위의 코드와 함께 DemoOfClientStatemain()의 출력은 다음과 같다:

monday
TUESDAY
WEDNESDAY
thursday
FRIDAY
SATURDAY
sunday

각주 편집

  1. Erich Gamma; Richard Helm; Ralph Johnson; John Vlissides (1994). 《Design Patterns: Elements of Reusable Object-Oriented Software》. Addison Wesley. 305ff쪽. ISBN 0-201-63361-2. 
  2. “The State design pattern - Structure and Collaboration”. 《w3sDesign.com》. 2017년 8월 12일에 확인함. 
  3. “State pattern in UML and in LePUS3”. 2016년 8월 5일에 원본 문서에서 보존된 문서. 2018년 3월 6일에 확인함. 
  4. “legend”. 2018년 3월 14일에 원본 문서에서 보존된 문서. 2018년 3월 6일에 확인함. 

외부 링크 편집