state pattern

작성자

카테고리:

제목 없음

[cpp]
#include <iostream>
#include <string>

using namespace std;

class GameLevel
{
public:
static GameLevel* CreateInstance() { return 0; }
virtual void SimpleAttack() = 0;
virtual void TurnAttack() = 0;
virtual void FlyingAttack() = 0;
};

class GameLevel0 : public GameLevel
{
public:
static GameLevel* CreateInstance()
{
if( pInstance_ == NULL ) pInstance_ = new GameLevel0;
return pInstance_;
}

virtual void SimpleAttack() { cout << "SimpleAttack()" << endl; }
virtual void TurnAttack() { cout << "Not Allowed" << endl; }
virtual void FlyingAttack() { cout << "Not Allowed" << endl; }

protected:
static GameLevel0 * pInstance_;
};
GameLevel0* GameLevel0::pInstance_ = 0;

class GameLevel1 : public GameLevel
{
public:
static GameLevel* CreateInstance()
{
if( pInstance_ == NULL ) pInstance_ = new GameLevel1;
return pInstance_;
}

virtual void SimpleAttack() { cout << "SimpleAttack()" << endl; }
virtual void TurnAttack() { cout << "TurnAttack()" << endl; }
virtual void FlyingAttack() { cout << "Not Allowed" << endl; }

protected:
static GameLevel1 * pInstance_;
};
GameLevel1 * GameLevel1::pInstance_ = NULL;

class GameLevel2 : public GameLevel
{
public:
static GameLevel* CreateInstance()
{
if( pInstance_ == NULL ) pInstance_ = new GameLevel2;
return pInstance_;
}

virtual void SimpleAttack() { cout << "SimpleAttack()" << endl; }
virtual void TurnAttack() { cout << "TurnAttack()" << endl; }
virtual void FlyingAttack() { cout << "FlyingAttack()" << endl; }

protected:
static GameLevel2 * pInstance_;
};
GameLevel2 * GameLevel2::pInstance_ = NULL;

class GamePlayer
{
public:
GamePlayer() { pGameLevel_ = GameLevel0::CreateInstance(); }

void Updatelevel( GameLevel * pLevel) { pGameLevel_ = pLevel; }

virtual void SimpleAttack() { pGameLevel_->SimpleAttack(); }
virtual void TurnAttack() { pGameLevel_->TurnAttack(); }
virtual void FlyingAttack() { pGameLevel_->FlyingAttack(); }

private:
GameLevel * pGameLevel_;
};

int main()
{
GamePlayer user1;

user1.SimpleAttack();
user1.TurnAttack();
user1.FlyingAttack();

cout << "———————" << endl;

user1.Updatelevel( GameLevel1::CreateInstance() );
user1.SimpleAttack();
user1.TurnAttack();
user1.FlyingAttack();

cout << "———————" << endl;

user1.Updatelevel( GameLevel2::CreateInstance() );
user1.SimpleAttack();
user1.TurnAttack();
user1.FlyingAttack();

cout << "———————" << endl;
return 0;
}

[/cpp]

구현관련 사항
– State패턴은 상태변화에 따라 행위 수행 변경이 자동으로 이루어 지게 만들기 위한 것. 상태변환을 쉽게 하기 위해 설계된것이 아님.

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다