유니티에서 전략 패턴(Strategy Pattern)은 특정한 알고리즘군을 정의하고 각각을 캡슐화하여 서로 교환 가능하도록 하는 패턴이다. 이 패턴을 사용하면 알고리즘을 사용하는 클라이언트와는 독립적으로 알고리즘을 변경할 수 있어 유연성이 높아진다.
장점
- 유연성: 알고리즘을 독립적으로 변경할 수 있어 확장성과 유지보수성이 높아진다.
- 재사용성: 다양한 알고리즘을 동일한 인터페이스를 통해 사용할 수 있다.
- 객체 간 결합도 감소: 전략 객체와 클라이언트 간의 결합도가 낮아져 객체들 간의 의존성이 줄어든다.
단점
- 클래스 증가: 많은 전략 클래스가 필요할 경우 클래스의 수가 증가할 수 있다.
- 패턴 이해와 구현의 복잡성: 처음에는 이해하기 어려울 수 있으며, 잘못된 사용으로 인해 복잡성이 증가할 수 있다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface IMovementStrategy
{
void Move(Transform transform);
}
// 구체적인 전략 1: 직선 이동
public class StraightMovement : IMovementStrategy
{
public float speed = 5f;
public void Move(Transform transform)
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
}
// 구체적인 전략 2: 지그재그 이동
public class ZigzagMovement : IMovementStrategy
{
public float speed = 3f;
public float frequency = 2f;
public float magnitude = 0.5f;
public void Move(Transform transform)
{
Vector3 pos = transform.position;
pos += transform.forward * speed * Time.deltaTime;
pos += transform.right * Mathf.Sin(Time.time * frequency) * magnitude;
transform.position = pos;
}
}
// 전략을 사용하는 컨텍스트 클래스
public class Character_1 : MonoBehaviour
{
private IMovementStrategy movementStrategy;
public void SetMovementStrategy(IMovementStrategy strategy)
{
movementStrategy = strategy;
}
void Update()
{
if (movementStrategy != null)
{
movementStrategy.Move(transform);
}
}
}
// 전략 패턴 사용 예시
public class GameManager_1 : MonoBehaviour
{
public Character_1 character;
void Start()
{
character = GetComponent<Character_1>();
// 초기 전략 설정
character.SetMovementStrategy(new StraightMovement());
}
void Update()
{
// 스페이스바를 누르면 전략 변경
if (Input.GetKeyDown(KeyCode.Space))
{
character.SetMovementStrategy(new ZigzagMovement());
}
}
}
게임 시작 시 캐릭터에게 초기 전략을 설정하고, 스페이스바를 누를 때마다 다른 움직임 전략으로 변경한다. 이는 게임 중에 캐릭터의 움직임을 동적으로 변화시킬 수 있는 기능을 제공한다.
'개인 공부 > 디자인패턴' 카테고리의 다른 글
| 유니티 반복자 (Iterator) (1) | 2024.07.19 |
|---|---|
| 유니티 중재자 (Mediator) (0) | 2024.07.19 |
| 유니티 메멘토 (1) | 2024.07.19 |
| 유니티 옵저버 (1) | 2024.07.19 |
| 유니티 FSM (0) | 2024.07.17 |