-----------------------------------------------------------------------------
[State]
의도:
객체 자신의 내부 상태에 따라 행위를 변경하도록 한다. 객체가 클래스를 바꾸는 것처럼 보일
수 있다.
다른 이름:
Object for State
설명:
FSM(Finite State Machine)를 구현함에 있어서 State패턴을 이용한다.
-----------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////
//
// A Behavioral part of GoF's Design Patterns
//
// - State
//
/////////////////////////////////////////////////////////////////////////////
#include <windows.h>
#include <tchar.h>
#include <iostream>
/////////////////////////////////////////////////////////////////////////////
//
// State
//
/////////////////////////////////////////////////////////////////////////////
class Context;
class State
{
public:
virtual ~State() {}
public:
virtual void Handle (Context*) {}
protected:
virtual void ChangeState (Context*, State*);
};
//// ------------------------------------------------------------------------
class ConcreteStateA : public State
{
public:
virtual void Handle(Context* c);
};
class ConcreteStateB : public State
{
public:
virtual void Handle(Context* c);
};
class ConcreteStateC : public State
{
public:
virtual void Handle(Context* c);
};
void ConcreteStateA::Handle(Context* c)
{
std::cout << "ConcreteStateA::Handle()" << std::endl;
ChangeState (c, new ConcreteStateB());
}
void ConcreteStateB::Handle(Context* c)
{
std::cout << "ConcreteStateB::Handle()" << std::endl;
ChangeState (c, new ConcreteStateC());
}
void ConcreteStateC::Handle(Context* c)
{
std::cout << "ConcreteStateC::Handle()" << std::endl;
ChangeState (c, new ConcreteStateA());
}
//// ------------------------------------------------------------------------
class Context
{
public:
friend class State;
public:
Context () : State_(0)
{
State_ = new ConcreteStateA();
}
virtual ~Context ()
{
if (State_)
delete State_;
}
public:
void Request (void)
{
if (State_)
{
State_->Handle(this);
}
}
protected:
void ChangeState (State *s)
{
if (State_)
{
delete State_;
}
State_ = s;
}
private:
State *State_;
};
//// ------------------------------------------------------------------------
void State::ChangeState (Context* c, State* s)
{
c->ChangeState (s);
}
/////////////////////////////////////////////////////////////////////////////
//
// Startup
//
//
/////////////////////////////////////////////////////////////////////////////
int _tmain(int argc, _TCHAR* argv[])
{
Context context;
context.Request();
context.Request();
context.Request();
context.Request();
context.Request();
context.Request();
return 0;
}
-----------------------------------------------------------------------------
ConcreteStateA::Handle()
ConcreteStateB::Handle()
ConcreteStateC::Handle()
ConcreteStateA::Handle()
ConcreteStateB::Handle()
ConcreteStateC::Handle()