Строитель (Builder) :: Cетевой уголок Majestio

Строитель (Builder)


Строитель — это порождающий паттерн проектирования, который позволяет создавать сложные объекты пошагово. Строитель даёт возможность использовать один и тот же код строительства для получения разных представлений объектов.

Применимость

Подробнее на 👉 refactoring.guru

UML-диаграмма

Пример реализации

#include <iostream>
#include <string>

class Car {
 public:
  std::string brand;
  std::string model;
  std::string color;
  int year;

  void info() {
    std::cout << "Brand: " << brand << std::endl;
    std::cout << "Model: " << model << std::endl;
    std::cout << "Color: " << color << std::endl;
    std::cout << "Year: " << year << std::endl;
  }
};

class CarBuilder {
 private:
  Car car;

 public:
  CarBuilder& setBrand(const std::string& brand) {
    car.brand = brand;
    return *this;
  }

  CarBuilder& setModel(const std::string& model) {
    car.model = model;
    return *this;
  }

  CarBuilder& setColor(const std::string& color) {
    car.color = color;
    return *this;
  }

  CarBuilder& setYear(int year) {
    car.year = year;
    return *this;
  }

  Car build() { return car; }
};

int main() {
  CarBuilder builder;
  Car car = builder.setBrand("Toyota")
                .setModel("Camry")
                .setColor("Red")
                .setYear(2022)
                .build();

  car.info();
  return 0;
}
Будет напечатано:
Brand: Toyota
Model: Camry
Color: Red
Year: 2022
class Car {
  final String brand;
  final String model;
  final String color;
  final int year;

  Car({
    required this.brand,
    required this.model,
    required this.color,
    required this.year,
  });

  void info() {
    print('Brand: $brand');
    print('Model: $model');
    print('Color: $color');
    print('Year: $year');
  }
}

class CarBuilder {
  String? brand;
  String? model;
  String? color;
  int? year;

  CarBuilder setBrand(String brand) {
    this.brand = brand;
    return this;
  }

  CarBuilder setModel(String model) {
    this.model = model;
    return this;
  }

  CarBuilder setColor(String color) {
    this.color = color;
    return this;
  }

  CarBuilder setYear(int year) {
    this.year = year;
    return this;
  }

  Car build() {
    return Car(
      brand: brand!,
      model: model!,
      color: color!,
      year: year!,
    );
  }
}

void main() {
  CarBuilder builder = CarBuilder();
  Car car = builder
      .setBrand('Toyota')
      .setModel('Camry')
      .setColor('Red')
      .setYear(2022)
      .build();

  car.info();
}
Будет напечатано:
Brand: Toyota
Model: Camry
Color: Red
Year: 2022
Рейтинг: 0/5 - 0 голосов