-
Notifications
You must be signed in to change notification settings - Fork 0
스테이트 패턴 (State pattern)
VG edited this page Dec 20, 2020
·
6 revisions
상태 패턴(state pattern)은 객체 지향 방식으로 상태 기계를 구현하는 행위 소프트웨어 디자인 패턴이다.출처: 위키백과
출처: 위키백과
상태(추상) 인터페이스
public interface State
{
public void Shot();
public void InsertBullet(int count);
}
상태 클래스
//총알이 비어있는 상태
public class BulletEmptyState : State
{
Gun gun;
public BulletEmptyState(Gun gun)
{
this.gun = gun;
}
public void InsertBullet(int count)
{
Console.WriteLine("총알 " + count + "발을 넣었다.");
gun.Bullets += count;
if (gun.Bullets > 0)
gun.SetState(gun.canShotState);// 총의 상태를 바꾼다. (총알이 비어있는 상태) → (총을 쏠 수 있는 상태)로 태세(상태) 변환
}
public void Shot()
{
Console.WriteLine("앗! 총알이 비어서 쏠 수 없다!\n");
}
}
//총을 쏠 수 있는 상태
public class CanShotState : State
{
Gun gun;
public CanShotState(Gun gun)
{
this.gun = gun;
}
public void InsertBullet(int count)
{
gun.Bullets += count;
Console.WriteLine("총알 " + count + "발을 넣었다.");
}
public void Shot()
{
Console.WriteLine("빵!");
gun.Bullets--;
if (gun.Bullets == 0)
gun.SetState(gun.bulletEmptyState);// 총의 상태를 바꾼다. (총을 쏠 수 있는 상태) → (총알이 비어있는 상태)로 태세(상태) 변환
}
}
상태 주인 클래스
public class Gun
{
public State canShotState { get; private set; }
public State bulletEmptyState { get; private set; }
private State currentState;
private int bullets;
public int Bullets
{
get
{
return bullets;
}
set
{
bullets = value;
Console.WriteLine("남은 총알: "+bullets+"발\n");
}
}
public Gun()
{
canShotState = new CanShotState(this);
bulletEmptyState = new BulletEmptyState(this);
currentState = bulletEmptyState;
}
public void SetState(State state)
{
currentState = state;
}
public void InsertBullet(int count)
{
currentState.InsertBullet(count);
}
public void Shot()
{
currentState.Shot();
}
}
메인 클래스
class MainClass
{
static void Main(string[] args)
{
Gun gun = new Gun();
gun.Shot();
gun.InsertBullet(3);
gun.Shot();
gun.Shot();
gun.Shot();
gun.Shot();
}
}
출력결과
앗! 총알이 비어서 쏠 수 없다!
총알 3발을 넣었다.
남은 총알: 3발
빵!
남은 총알: 2발
빵!
남은 총알: 1발
빵!
남은 총알: 0발
앗! 총알이 비어서 쏠 수 없다!
전략 패턴과 상태 패턴의 구조는 매우 비슷하다.


공통점
- 하나의
주체자
가 여러상태
나전략
에 의존하고 있다.
차이점
- 전략 패턴에서는
전략
에서전략
으로 자신의전략
을 변경하지 않는다. - 상태 패턴에서는
상태
에서상태
로 자신의상태
를 변경한다.
이렇게, 둘은 같은 구조를 가지고 있지만, 다른 용도나 목적을 가지고있다.
여러 출처를 바탕으로 최대한 오류를 범하지 않도록 작성하였으나, 이 페이지를 작성하는 저 또한 해당 학문을 공부하는 학생입니다.
∴해당 페이지의 정보를 맹신하지 마시길 바랍니다.
-
생성 패턴
-
구조 패턴
- 데코레이터 패턴 (Decorator pattern)
- 어댑터 패턴 (Adapter pattern)
- 퍼사드 패턴 (Facade pattern)
- 프록시 패턴 (Proxy pattern)
- 이터레이터, 컴포지트 패턴 (Iterator, Composite pattern)
-
동작 패턴
- 옵저버 패턴 (Observer pattern)
- 템플릿 메소드 패턴 (Template pattern)
- 커맨드 패턴 (Command pattern)
- 스트래티지 패턴 (Strategy pattern)
- 스테이트 패턴 (State pattern)
-
기타 패턴
- 컴파운드 패턴 (Compound pattern)
- 메소드 체이닝 (Method chaining)
- Dispose 패턴 (Dispose pattern)