patterns/builder.dart

73 lines
1.8 KiB
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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