'Developer/Design Patterns'에 해당되는 글 27건

  1. 2014.05.18 State Pattern

//객체의 상태를 변경하는 설계 기법 - 상태(state) 패턴

#include <iostream>

using namespace std;

 

// 상태에 따른 동작을 정의하는 인터페이스를 정의한다

struct IState {

        virtual ~IState() {}

        virtual void runImpl() = 0;

        virtual void attackImpl() = 0;

};

 

class Character {

        int hp;

        IState *state;

 

public:

        void setState(IState* p) { state = p; }

        void run() { state->runImpl(); }

        void attack() { state->attackImpl(); }

};

 

class NormalCharacter : public IState {

public:

        void runImpl() { cout << "NormalCharacter::Run" << endl; }

        void attackImpl() { cout << "NormalCharacter::Attack" << endl; }

};

 

class Item1Character : public IState {

public:

        void runImpl() { cout << "Item1Character::Run" << endl; }

        void attackImpl() { cout << "Item1Character::Attack" << endl; }

};

 

 

int main() {

        Character c;

 

        NormalCharacter nc;

        c.setState(&nc);

        c.run();

        getchar();

 

        //아이템이 적용된 케릭터

        Item1Character ic;

        c.setState(&ic);

        c.run();

}

 

Posted by No names
,