Prototype 예시 (Character)
#pragma once
/*=================================
Prototype Pattern
=================================*/
/*
프로토 타입 패턴은 객체 생성 방식 중 하나로 기존의 객체를 복제하여 새로운 객체를 만드는
패턴 방식이다.
객체 생성 비용이 높은 경우 유용하다.
장점
ㄴ 효율성 : 불필요한 초기화 작업을 생략하고 복사를 통해 객체를 생성 한다.
ㄴ 유연성 : 객체의 구체적인 클래스를 알 필요 없이 복제된 객체를 생성 한다.
단점
ㄴ 복잡함 : 포인터 또는 참조 타입이 포함된 경우 복사 메커니즘을 명확히 정의 해야한다.
ㄴ 성능 : 복사 작업이 빈번하게 발생하면 서능이 저하될 수 있다.
ㄴ 타입 안정성 : 잘못된 타입으로 접근할 수 있어 추가적인 타입 체크가 필요하다.
*/
class Character
{
public:
virtual ~Character() {}
protected:
Character() {}
Character(int hp, int mp, int speed)
: _hp(hp), _mp(mp), _speed(speed)
{}
public:
int getHP() const
{
return _hp;
}
int getMP() const
{
return _mp;
}
int getSpeed() const
{
return _speed;
}
string getName() const
{
return _name;
}
void setHP(int health)
{
_hp = health;
}
void setMP(int magic)
{
_mp = magic;
}
void setSpeed(int spd)
{
_speed = spd;
}
void setName(const string& name)
{
_name = name;
}
public:
virtual unique_ptr<Character> clone() const = 0;
virtual void display() const = 0;
virtual void attack() = 0;
private:
string _name;
int _hp = 0;
int _mp = 0;
int _speed = 0;
};
Character 클래스를 상속 (Mage)
#pragma once
#include "Character.h"
class Mage : public Character
{
public:
Mage() {}
Mage(int hp, int mp, int speed)
: Character(hp, mp, speed)
{}
~Mage() {}
public:
unique_ptr<Character> clone() const override
{
return make_unique<Mage>(*this);
}
void display() const override
{
std::cout << "Mage: " << getName()
<< ", HP: " << getHP()
<< ", MP: " << getMP()
<< ", Speed: " << getSpeed() << "\n";
}
void attack() override
{
cout << "Mage 기본 공격\n";
}
public:
void skill()
{
cout << "Mage 스킬 공격\n";
}
};
Character 클래스를 상속 (Warrior)
#pragma once
#include "Character.h"
class Warrior : public Character
{
public:
Warrior(int hp, int mp, int speed)
: Character(hp, mp, speed)
{}
~Warrior() {}
public:
unique_ptr<Character> clone() const override
{
return make_unique<Warrior>(*this);
}
void display() const override
{
std::cout << "Warrior: " << getName()
<< ", HP: " << getHP()
<< ", MP: " << getMP()
<< ", Speed: " << getSpeed() << "\n";
}
void attack() override
{
cout << "Warrior 기본 공격\n";
}
public:
void skill()
{
cout << "Warrior 스킬 공격\n";
}
};
Prototype 사용
#include "pch.h"
#include "Mage.h"
#include "Warrior.h"
int main()
{
Mage prototypeMage(100, 100, 10);
Warrior prototypeWarrior(200, 50, 10);
unique_ptr<Character> copyMage = prototypeMage.clone();
unique_ptr<Character> copyWarrior = prototypeWarrior.clone();
/*
런타임에 타입체크가 필요할 시 dynamic_cast사용
*/
copyMage->attack();
static_cast<Mage*>(copyMage.get())->skill();
copyWarrior->attack();
static_cast<Warrior*>(copyWarrior.get())->skill();
return 0;
}
'Design Pattern' 카테고리의 다른 글
State Pattern (0) | 2024.02.06 |
---|---|
Observer Pattern (0) | 2024.02.05 |
Builder Pattern (0) | 2024.02.03 |
Factory Pattern (0) | 2024.02.02 |
Singleton Pattern (0) | 2024.02.01 |