본문 바로가기

카테고리 없음

05. 프로토타입

원형이 되는 인스턴스를 사용하여 생성할 객체의 종류를 명시하고, 이렇게 만든 견본을 복사하여 새로운 객체를 생성한다.

 

5.1 프로토타입 디자인패턴

나쁜코드

class Monster
{}

class Ghost : public Monster
{}

class Demon : public Monster
{}

...


class Spawner
{}

class GhostSpawner : public Spanwer
{}

class DemonSpawner : public Spawner
{}

 

 

프로토 타입 패턴 - 도장찍듯이

어떤 객체가 자기와 비슷한 객체를 스폰할 수 있다

class Monster
{
virtual Monster* clone() = 0;
}

class Ghost : public Monster
{
public:
	Ghost(int32 inHP, int32 inMP)
    : HP_(inHP)
    , MP_(inMP)
    {}
    
    virtual Monster* clone()
    {
    	return new Ghost(HP_, MP_);
    }
private:
    int32 HP_;
    int32 MP_;
}

...


class Spawner
{
public:
    Spawner(Monster* prototype) 
    : prototype_(prototype)
    {}
	
    Monster* spawnMonster()
    {
    	return prototype_->clone();
    }
private:
	//벌집을 떠나지 않는 여왕벌처럼 Monster객체를 도장찍듯 만들어내는 스포너 역할만 한다.
	Monster* prototype_;
}


//사용
Monster* ghostPrototype = new Ghost(3, 4);
Spawner* ghostSpawner = new Spawner(ghostPrototype);

클래스 뿐 아니라 상태도 같이 복제되므로 빠른 유령, 약한 유령... 스포너를 쉽게 만들 수 있다.

 

 

템플릿 프로토타입

class Spawner
{
public:
	virtual ~Spawner(){}
    virtual Monster* spawnMonster() = 0;
};

template <class T>
class SpawnerFor : public Spawner
{
public:
    virtual Monster spanwerMosnter() {return new T();}
};

//사용
Spawner* ghostSpanwer = new SpawerFor<Ghost>();

짱이다..

 

 

5.2 프로토타입 언어패러다임

프로토타입이  OOP를 해친다고??

위임

 

OOP : 데이터와 코드를 묶어주는 '객체'를 직접 지정할 수 있게 한다.