patterns/builder.dart

73 lines
1.8 KiB
Dart
Raw Normal View History

2022-03-29 09:52:34 +03:00
// предоставляет способ создания составного объекта
2022-03-01 10:30:23 +03:00
class PizzaBuilder {
late String _crust;
int _diameter;
late Set<String> _toppings;
PizzaBuilder(this._diameter);
String get crust => _crust;
2022-03-29 10:11:19 +03:00
set crust(String newCrust) => _crust = newCrust;
2022-03-01 10:30:23 +03:00
int get diameter => _diameter;
2022-03-29 10:11:19 +03:00
set diameter(int newDiameter) => _diameter = newDiameter;
2022-03-01 10:30:23 +03:00
Set<String> get toppings => _toppings;
set toppings(Set<String> newToppings) {
_toppings = newToppings;
2022-03-29 10:11:19 +03:00
_addCheese();
2022-03-01 10:30:23 +03:00
}
2022-03-29 10:11:19 +03:00
void _addCheese() => _toppings.add("сыр");
2022-03-01 10:30:23 +03:00
Pizza build() {
return Pizza(this);
}
}
class Pizza {
late String _crust;
late int _diameter;
late Set<String> _toppings;
Pizza(PizzaBuilder builder) {
_crust = builder.crust;
_diameter = builder.diameter;
_toppings = builder.toppings;
}
String get crust => _crust;
int get diameter => _diameter;
String get toppings => _stringifiedToppings();
String _stringifiedToppings() {
var stringToppings = _toppings.join(", ");
var lastComma = stringToppings.lastIndexOf(",");
2022-03-29 10:11:19 +03:00
var replacement = ",".allMatches(stringToppings).length > 1 ? ", и" : " и";
2022-03-01 10:30:23 +03:00
return stringToppings.replaceRange(lastComma, lastComma + 1, replacement);
}
@override
String toString() {
2022-03-29 10:11:19 +03:00
return "Пицца с $_diameter\" диметром с $_crust корочкой. Ингридиенты: $toppings";
2022-03-01 10:30:23 +03:00
}
}
void main() {
var pizzaBuilder = PizzaBuilder(8);
2022-03-29 10:11:19 +03:00
pizzaBuilder.crust = "хрустящей";
pizzaBuilder.toppings = Set.from(["пеперони"]);
2022-03-01 10:30:23 +03:00
var plainPizza = Pizza(pizzaBuilder);
2022-03-29 10:11:19 +03:00
print("Заказана $plainPizza.");
2022-03-01 10:30:23 +03:00
2022-03-29 10:11:19 +03:00
pizzaBuilder.crust = "сырной";
pizzaBuilder.diameter = 10;
pizzaBuilder.toppings = Set.from(["ананасы"]);
2022-03-01 10:30:23 +03:00
2022-03-29 10:11:19 +03:00
var ananasPizza = pizzaBuilder.build();
print("Заказана $ananasPizza!");
2022-03-01 10:30:23 +03:00
}