오늘 학습 키워드
리팩토링, 커맨드 패턴
오늘 학습 한 내용을 나만의 언어로 정리하기
숫자 판단하기
// 기존 코드
bool isNumber(string str)
{
if (str[0] - '0' >= 0 && str[0] - '0' < 10) return true;
else return false;
}
// 수정 코드
bool isNumber(string str)
{
return int.TryParse(str, out _);
}
int.TryParse의 반환값은 변환에 성공했는지 여부. out _ 에 들어오는건 변환된 정수값.
switch-case 문을 커맨드 패턴으로 바꾸기
커맨드 패턴 : 요청을 캡슐화해서 호출자와 실행 로직을 분리.
커맨드 패턴의 4가지 구성 요소
번호 | 역할 이름 | 설명 |
---|---|---|
① | 요청자 (Invoker) | 명령을 실행할 타이밍만 알고 있음. 예: 리모컨, 버튼 |
② | 커맨드 인터페이스 (Command) | 모든 명령의 공통 인터페이스 (Execute() ) |
③ | 명령 객체 (ConcreteCommand) | 실제 명령 실행 로직을 담고 있는 클래스 |
④ | 수신자 (Receiver) | 명령을 실제로 수행하는 객체. 예: 조명, TV, 캐릭터 등 |
// 예시 코드
// 1. 요청자
public class RemoteButton
{
private ICommand command; // 커맨드 인터페이스
public RemoteButton(ICommand command)
{
this.command = command;
}
public void Press()
{
command.Execute();
}
}
// 2. 커맨드 인터페이스
public interface ICommand
{
void Execute();
}
// 3. 명령 객체
public class LightOnCommand : ICommand
{
private Light light;
public LightOnCommand(Light light)
{
this.light = light;
}
public void Execute()
{
light.TurnOn();
}
}
public class LightOffCommand : ICommand
{
private Light light;
public LightOffCommand(Light light)
{
this.light = light;
}
public void Execute()
{
light.TurnOff();
}
}
// 4. 수신자
public class Light
{
public void TurnOn()
{
Debug.Log("불이 켜졌습니다.");
}
public void TurnOff()
{
Debug.Log("불이 꺼졌습니다.");
}
}
⇒ 지금까지 짰던 Switch-case문을 커맨드 패턴으로 바꾸자.
// ICalculatoCommand.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface ICalculatorCommand
{
void Execute(CalculatorPresenter presenter);
}
// CalculatorPresenter.cs
public void OnOperatorInput(string str)
{
if (commandTable.TryGetValue(str, out var command))
{
command.Execute(this);
}
else
{
Debug.LogWarning($"Unknown input: {str}");
}
Refresh();
}
// AddCommand.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddCommand : ICalculatorCommand
{
public void Execute(CalculatorPresenter presenter)
{
presenter.PrepareOperand("+");
}
}
드디어 코드도 깔끔하게 해서 완성
학습하며 겪었던 문제점 & 에러
- 문제&에러에 대한 정의
같은 기수 분이 할당 오류가 떴음
- 내가 한 시도
프리팹을 수정하고자 함
- 해결 방법
프리팹을 오버라이드 하지 않으셔서 제대로 변경되지 않음
- 이 문제&에러를 다시 만나게 되었다면?
프리팹이 제대로 바뀐게 맞나 확인을 재차 해야겠다
내일 학습 할 것은 무엇인지
달리기반 퀘스트를 진행할 예정.
사람 안구해지면 계산기 로직 좀 더 수정하거나, 다른 유니티 강의 보면서 게임 제작 할 예정