정의
- 복잡한 인스턴스를 조립해서 만드는 구조
- 복합 객체를 생성할 때 객체를 생성하는 방법과 객체를 구현하는 방법을 분리함으로써 동일한 생성 절차에서 서로 다른 표현 결과를 만들 수 있음
- 생성과 표기를 분리해서 복잡한 객체를 생성
유니티에서 예를 들어보자
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NoBuilderData
{
public int a;
public int b;
public int c;
public int d;
public int e;
public void Print()
{
Debug.Log($"a : {a} b : {b} c : {c} d : {d} e : {e}");
}
}
public class BuilderData
{
private int a;
private int b;
private int c;
private int d;
private int e;
public void Print()
{
Debug.Log($"a : {a} b : {b} c : {c} d : {d} e : {e}");
}
public BuilderData SetA(int v)
{
a = v;
return this;
}
public BuilderData SetB(int v)
{
b = v;
return this;
}
public BuilderData SetC(int v)
{
c = v;
return this;
}
public BuilderData SetD(int v)
{
d = v;
return this;
}
public BuilderData SetE(int v)
{
e = v;
return this;
}
}
public class Builder : MonoBehaviour
{
private NoBuilderData _noBuilderData;
private BuilderData _builderData;
public List<Action> NoBuilderActions = new();
public List<Action> BuilderActions = new();
Builder AddAction(Action action)
{
BuilderActions.Add(action);
return this;
}
void ExcuteActions()
{
foreach (var builderAction in BuilderActions)
{
builderAction.Invoke();
}
}
void Start()
{
//노빌더
_noBuilderData = new NoBuilderData
{
a = 10,
b = 10,
c = 10,
d = 10,
e = 10
};
_noBuilderData.Print();
//빌더
_builderData = new BuilderData();
_builderData.SetA(10).SetB(10).SetC(10).SetD(10).SetE(10).Print();
//실제 활용 사례 (노 빌더)
NoBuilderActions.Add(()=>{Debug.Log("a");});
NoBuilderActions.Add(()=>{Debug.Log("b");});
NoBuilderActions.Add(()=>{Debug.Log("c");});
NoBuilderActions.Add(()=>{Debug.Log("d");});
NoBuilderActions.Add(()=>{Debug.Log("e");});
foreach (var noBuilderAction in NoBuilderActions)
{
noBuilderAction.Invoke();
}
// 실제 활용 사례 (빌더)
AddAction(() => {Debug.Log("a");}).
AddAction(() => {Debug.Log("b");}).
AddAction(() => {Debug.Log("c");}).
AddAction(() => {Debug.Log("d");}).
AddAction(() => {Debug.Log("e");}).ExcuteActions();
}
}
스크립트로 작성한 빌더 디자인패턴과 일반 생성 방식이다.
차이점
코드에서는 각 방식으로 객체를 생성하고, 이후에 각 객체의 데이터를 출력하고 실행하는 방법을 보여준다. 빌더 패턴을 사용한 BuilderData 클래스는 속성 설정이 메서드 체이닝으로 이루어지며, 객체 생성 시 일부 속성만 선택적으로 설정할 수 있는 유연성을 제공하는 반면 NoBuilderData 클래스는 모든 속성을 한 번에 설정하는 방식으로, 초기화 과정이 단순하고 직관적이다.
결론
- 빌더 패턴은 객체 생성 과정이 복잡하고, 선택적으로 설정할 속성이 많을 때 유용하다. 코드의 가독성과 유지보수성을 높이는 데 용이하다.
- 일반적인 객체 생성 방식은 초기화 과정이 간단하고 직관적일 때 유용하며, 대부분의 속성이 필수적으로 설정되어야 할 때 적합하다.
'개인 공부 > 디자인패턴' 카테고리의 다른 글
| 디자인패턴 데코레이터 (0) | 2024.07.15 |
|---|---|
| 디자인패턴 브릿지 (0) | 2024.07.15 |
| 디자인패턴 싱글톤 (0) | 2024.07.12 |
| 디자인패턴 프로토타입 (0) | 2024.07.12 |
| 디자인패턴 추상팩토리 (2) | 2024.07.12 |