(C#)디자인패턴 - 빌더 패턴

티원·2025년 10월 4일

디자인패턴

목록 보기
2/16

빌더 패턴

(많이 쓰지는 않는 것 같다)
생성자가 너무 많은 경우 어디에 무엇을 넣을지 헷갈려 실수가 발생할 수 있음
빌더 패턴으로 생성자를 순서에 상관없이 설정할 수 있다.

쓰는 이유 예시

아래 코드에서 생성자가 너무 많은 경우 헷갈려서 실수가 발생할 수 있다.
그래서 빌더 패턴을 사용할 수 있음

public class StudentScore
{
    public int Kor;
    public int Eng;
    public int Mat;
    public int Sci;
    public int Soc;
    public StudentScore(int _kor,int _eng, int _mat, int _sci, int _soc)
    {
        Kor = _kor; Eng = _eng; Mat = _mat; Sci = _sci; Soc = _soc;
    }
}

코드

public class ScoreBuilder
{
    private StudentScore studentScore;
    public ScoreBuilder()
    {
        studentScore = new StudentScore(0, 0, 0, 0,0);
    }
    public ScoreBuilder SetKor(int value)
    {
        studentScore.Kor = value;
        return this;
    }
    public ScoreBuilder SetEng(int value)
    {
        studentScore.Eng = value;
        return this;
    }
    public ScoreBuilder SetMat(int value)
    {
        studentScore.Mat = value;
        return this;
    }
    public StudentScore Return()
    {
        return studentScore;
    }
}

public class StudentScore
{
    public int Kor;
    public int Eng;
    public int Mat;
    public int Sci;
    public int Soc;
    public StudentScore(int _kor,int _eng, int _mat, int _sci, int _soc)
    {
        Kor = _kor; Eng = _eng; Mat = _mat; Sci = _sci; Soc = _soc;
    }
}
static void Main(string[] args)
{
    ScoreBuilder scoreBuilder = new ScoreBuilder();
    scoreBuilder.SetEng(10).SetKor(20).SetMat(80);
    ScoreBuilder scoreBuilder2 = new ScoreBuilder();
    //▼ StudentScore형으로 반환도 가능
    StudentScore studentScore = scoreBuilder2.SetMat(50).SetEng(60).SetKor(70).Return(); 
}

0개의 댓글