프로그래밍/C#

[C#] 디자인 패턴 - Builder Pattern

흔한티벳여우 2023. 8. 15. 15:18
반응형

Builder Pattern은 복잡한 객체의 생성을 단순화하기 위한 디자인 패턴입니다. 객체의 생성과 표현을 분리함으로써 동일한 생성 절차에서 서로 다른 표현 결과를 얻을 수 있습니다.

 

기본 구조

Builder Pattern은 주로 다음 구성 요소로 이루어져 있습니다:

  1. Builder: 생성될 객체의 각 부분의 생성과 조립 방법을 정의하는 추상 인터페이스입니다.
  2. ConcreteBuilder: Builder의 인터페이스를 구현하는 클래스로, 실제 제품의 구체적인 표현을 정의합니다.
  3. Director: Builder 인터페이스의 사용 방법을 정의합니다.
  4. Product: 생성될 복잡한 객체를 나타냅니다.

언제 사용해야 하는가?

  1. 복잡한 객체의 생성 절차와 그 표현을 분리하고 싶을 때
  2. 동일한 생성 절차에서 서로 다른 표현을 얻고자 할 때
  3. 객체 생성에 필요한 절차를 더 세분화하고 싶을 때

As-Is 예시 (Builder Pattern 사용 전)

public class Car
{
    public Car(string engine, string tires, string seats, string radio)
    {
        // Car 생성 로직
    }
}

To-Be 예시 (Builder Pattern 사용 후)

// Product
public class Car
{
    public string Engine { get; set; }
    public string Tires { get; set; }
    public string Seats { get; set; }
    public string Radio { get; set; }
}

// Builder
public abstract class CarBuilder
{
    protected Car _car = new Car();

    public Car GetCar() => _car;

    public abstract void SetEngine();
    public abstract void SetTires();
    public abstract void SetSeats();
    public abstract void SetRadio();
}

// ConcreteBuilder
public class SportsCarBuilder : CarBuilder
{
    public override void SetEngine()
    {
        _car.Engine = "High Performance Engine";
    }

    public override void SetTires()
    {
        _car.Tires = "Racing Tires";
    }

    public override void SetSeats()
    {
        _car.Seats = "Sports Seats";
    }

    public override void SetRadio()
    {
        _car.Radio = "Premium Audio System";
    }
}

// Director
public class CarDirector
{
    public void Construct(CarBuilder builder)
    {
        builder.SetEngine();
        builder.SetTires();
        builder.SetSeats();
        builder.SetRadio();
    }
}
반응형