Skip to content

상태 패턴은 상태 패턴 인터페이스의 파생 클래스로서 각각의 상태를 구현함으로써, 상태를 객체화시키고 상태전이 메서드를 구현할 필요 없이 상태객체가 슈퍼클래스에 의해 정의한 메소드를 호출하여 사용하도록 하는 패턴이다. 상태 전이를 위한 조건 로직이 복잡한 경우 이를 해소하기 위해 사용될 수 있다.


예시 코드

public interface State {
State feelingBetter();
State feelingBad();
void printCurrentEmotion();
}
public class Happy implements State{
@Override
public State feelingBetter() {
return this;
}
@Override
public State feelingBad() {
return new SoSo();
}
@Override
public void printCurrentEmotion() {
System.out.println("기분이 좋다");
}
}
public class SoSo implements State{
@Override
public State feelingBetter() {
return new Happy();
}
@Override
public State feelingBad() {
return new Bad();
}
@Override
public void printCurrentEmotion() {
System.out.println("기분이 그저그렇습니다");
}
}
public class Bad implements State{
@Override
public State feelingBetter() {
return new SoSo();
}
@Override
public State feelingBad() {
return this;
}
@Override
public void printCurrentEmotion() {
System.out.println("기분이 좋지 않습니다");
}
}

State 인터페이스를 상속받은 Happy, SoSo, Bad 세개의 상태 객체가 있다.


@AllArgsConstructor
public class Human {
private State state;
public void goodSituation() {
System.out.println("좋은 일이 생겼습니다");
state = state.feelingBetter();
state.printCurrentEmotion();
System.out.println();
}
public void badSituation() {
System.out.println("나쁜 일이 생겼습니다");
state = state.feelingBad();
state.printCurrentEmotion();
System.out.println();
}
}

그리고 상태 객체를 가지고있는 Human이 있다. Human에게는 좋은일이 생길 수도 있고, 나쁜 일이 생길 수도 있는데 각 상황에서는 기분이 좋아지거나 나빠진다.


public class App {
public static void main(String[] args) {
Human human = new Human(new SoSo());
human.goodSituation();
human.badSituation();
human.badSituation();
}
}
//실행 결과
좋은 일이 생겼습니다
기분이 좋습니다
나쁜 일이 생겼습니다
기분이 그저그렇습니다
나쁜 일이 생겼습니다
기분이 좋지 않습니다

Human 인스턴스 생성 후 좋은일과 나쁜 일을 만들어주면 위와 같이 출력되는 것을 볼 수 있다. 어떤 상태인지 if또는 switch문으로 확인 후 로직을 실행해줄 필요 없이, 상태 객체가 어떤 클래스냐에 따라 자동으로 그 상태에 맞는 로직이 실행되는 것을 볼 수 있다.

링크로 가면 코드를 볼 수 있다.