Strategy Pattern
전략 패턴(strategy pattern)은 객체가 할 수 있는 행위들을 전략 클래스를 생성하여 이에 위임하고, 객체의 행위를 바꾸고 싶은 경우 직접 수정하지 않고 전략을 바꿔주는 것을 의미한다.
다시 말하자면, 행위에 대한 알고리즘을 클래스로 정의하고 캡슐화하여 객체의 행위를 변경하고 싶은 경우 캡슐화한 알고리즘을 변경함으로써 유연하게 확장하는 패턴이다.
따라서 객체가 행위를 상속받거나 내부에서 직접 구현하는 것이 아니라 전략 클래스로 구성(Composition)된 행위들을 부여받는다.
전략 패턴의 구조는 다음과 같이 구성된다.
Strategy Interface : 행위에 대한 알고리즘을 캡슐화하는 인터페이스
Strategy Controller : 전략 인터페이스를 부여받아 실제로 알고리즘을 사용하는 클래스
Concrete Strategy : 인터페이스를 구현하여 실제 알고리즘을 정의하는 클래스
몬스터가 플레이어를 공격하는 방식이 거리에 따라 달라지는 것을 예시로 들어보자.
Strategy Interface
public interface IAttackStrategy
{
public void Attack(Transform attacker, Transform target)
}
Strategy Controller
public class EnemyController : MonoBehaviour
{
public Transform player;
private IAttackStrategy attackStrategy;
private void Start()
{
float distance = Vector3.Distance(transform.position, player.position);
if(distance < 3f)
{
attackStrategy = new MeleeAttack();
}
else
{
attackStrategy = new RangedAttack();
}
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
attackStrategy?.Attack(transform, player);
}
}
}
MeleeAttack
public class MeleeAttack : IAttackStrategy
{
public void Attack(Transform attacker, Transform target)
{
Debug.Log("근접 공격");
}
}
RangedAttack
public class RangedAttack : IAttackStrategy
{
public void Attack(Transform attacker, Transform target)
{
Debug.Log("원거리 공격");
}
}