[C#] Strategy Pattern

Lingtea_luv·2025년 5월 16일
0

C#

목록 보기
36/37
post-thumbnail

Strategy Pattern


개요

전략 패턴(strategy pattern)은 객체가 할 수 있는 행위들을 전략 클래스를 생성하여 이에 위임하고, 객체의 행위를 바꾸고 싶은 경우 직접 수정하지 않고 전략을 바꿔주는 것을 의미한다.

다시 말하자면, 행위에 대한 알고리즘을 클래스로 정의하고 캡슐화하여 객체의 행위를 변경하고 싶은 경우 캡슐화한 알고리즘을 변경함으로써 유연하게 확장하는 패턴이다.

따라서 객체가 행위를 상속받거나 내부에서 직접 구현하는 것이 아니라 전략 클래스로 구성(Composition)된 행위들을 부여받는다.

장단점

장점

  1. 개방폐쇄의 원칙 : 기존 코드를 수정할 필요 없이 신규 전략을 추가하는 것이 가능하다.
  2. 런타임 변경 가능 : 플레이 중 전략을 바꿀 수 있어 동적인 게임 플레이에 유리하다.

단점

  1. 구조 복잡도 증가 : 전략이 증가함에 따라 클래스가 추가되어 구조가 복잡해진다.
  2. 오버 엔지니어링 : 단순한 구조의 경우 오버 엔지니어링이 될 수 있다.

구조

전략 패턴의 구조는 다음과 같이 구성된다.

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("원거리 공격");	
    }
}
profile
뚠뚠뚠뚠

0개의 댓글