2016년 1월 24일 일요일

State Pattern (상태 패턴)

의도
  • 객체의 상태에 따라 스스로 행동을 변경할 수 있게 하는 패턴
이럴 때 사용하자.
  • 객체의 행동이 상태에 따라 달라지며, 런타임 시에 행동이 바뀌어야 할 때
  • 다중 분기 조건 처리가 너무 많을 때
장점은?
  • 상태에 따른 행동을 국소화하며, 서로 다른 상태에 대한 행동을 별도의 객체로 관리
  • 상태 전이를 명확하게 만듦
  • 상태 객체는 공유될 수 있음
코드
State 클래스
class State
{
public:
   virtual void Handle() = 0;
};

ConcreteStateA, ConcreteStateB 클래스
class ConcreteStateA : public State
{
public:
   void Handle() {
      cout << "ConcreteStateA" << endl;
   };
};

class ConcreteStateB : public State
{
public:
   void Handle() {
      cout << "ConcreteStateB" << endl;
   };
};

Context 클래스
class Context
{
public:
   Context(State* pState)
      : m_pState(pState) {};
   ~Context() {
      m_pState = NULL;
   };

   void SetState(State* pState) {
      m_pState = pState;
   };
   void Request() {
      m_pState->Handle();
   };
private:
   State* m_pState;
};

실행부분
void main()
{
   State* pConcreteStateA = new ConcreteStateA();
   State* pConcreteStateB = new ConcreteStateB();

   Context* pContext = new Context(pConcreteStateA);
   pContext->Request();

   pContext->SetState(pConcreteStateB);
   pContext->Request();

   delete pConcreteStateA;
   delete pConcreteStateB;
   delete pContext;
}
UML - class 다이어그램
참고
  • GoF의 디자인 패턴(개정판) 재사용성을 지닌 객체지향 소프트웨어의 핵심요소
  • http://joochang.tistory.com/64
  • http://blog.naver.com/gp_jhkim/220519499252
  • http://hunnywind.tistory.com/105

댓글 없음:

댓글 쓰기

참고: 블로그의 회원만 댓글을 작성할 수 있습니다.