Prototype의 정의
###프로토타입 패턴은 객체 생성이 높은 경우, 기존 객체를 복제하여 새로운 객체를 생성하는 디자인 패턴이다
왜 사용하는가?
상속과 활용
복제할 객체를 정의하는 인터페이스 또는 추상 클래스입니다.
이는 복제 메서드를 정의하고, 해당 메서드를 통해 객체를 복제합니다.
비용이 낮은 객체 생성
일반적으로 어떤 객체를 생성하는데에는 많은 자원이 소모되지만, 한번 생성 후 이를 복제하여 사용하면 많은 비용이 절약된다.
상태를 공유할 필요가 적은 경우
프로토타입 패턴으로 객체가 복제되면 독립적인 상태를 가질 수 있다. 대표적으로 총알이 그러하다
public class Player : MonoBehaviour
{
[SerializeField]
private Weapon currentWeapon;
[SerializeField]
private Target target;
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
currentWeapon.Attack(target);
}
}
}
public class Target : MonoBehaviour
{
private int currentHp = 100;
public void TakeDamage(int toDamage)
{
currentHp -= toDamage;
Debug.Log($"Damage Amount : {toDamage}");
}
}
public abstract class Weapon : MonoBehaviour
{
public void Attack(Target target)
{
DoAttack(target);
Debug.Log($"You have {DamageMessage()}");
}
protected abstract void DoAttack(Target target);
protected virtual string DamageMessage() { return "Hit"; }
}
public class Swrod : Weapon
{
protected override void DoAttack(Target target)
{
target.TakeDamage(10);
}
protected override string DamageMessage()
{
return "Basic Sword";
}
}
public class BigSword : Weapon
{
protected override void DoAttack(Target target)
{
target.TakeDamage(20);
}
protected override string DamageMessage()
{
return "BIG Sword";
}
}
public class MegaSword : Weapon
{
protected override void DoAttack(Target target)
{
target.TakeDamage(30);
}
protected override string DamageMessage()
{
return "Mega Sword";
}
}
어떤 상황에서 사용할 것 인가?