2022-03-29 09:52:34 +03:00
|
|
|
|
//предназначен для динамического подключения дополнительного поведения к объекту
|
|
|
|
|
|
2022-03-01 10:30:23 +03:00
|
|
|
|
abstract class Beverage {
|
|
|
|
|
double get cost;
|
|
|
|
|
String get ingredients;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
class Ingredient {
|
|
|
|
|
double cost;
|
|
|
|
|
String name;
|
|
|
|
|
|
|
|
|
|
Ingredient(this.name, this.cost);
|
|
|
|
|
|
|
|
|
|
@override
|
|
|
|
|
String toString() => this.name;
|
|
|
|
|
}
|
|
|
|
|
|
2022-03-29 09:52:34 +03:00
|
|
|
|
var coffee = Ingredient("кофе", .25);
|
|
|
|
|
var milk = Ingredient("молоко", .5);
|
|
|
|
|
var sugar = Ingredient("сахар", .1);
|
2022-03-01 10:30:23 +03:00
|
|
|
|
|
|
|
|
|
class Coffee implements Beverage {
|
|
|
|
|
Set<Ingredient> _ingredients = Set.from([coffee, milk, sugar]);
|
|
|
|
|
double get cost => _ingredients.fold(0, (total, i) => total + i.cost);
|
|
|
|
|
String get ingredients {
|
2022-03-29 09:52:34 +03:00
|
|
|
|
var stringIngredients =
|
|
|
|
|
_ingredients.fold("", (String str, i) => str + "${i.name}, ");
|
|
|
|
|
var trimmedString =
|
|
|
|
|
stringIngredients.substring(0, stringIngredients.length - 2);
|
2022-03-01 10:30:23 +03:00
|
|
|
|
var lastComma = trimmedString.lastIndexOf(",");
|
2022-03-29 09:52:34 +03:00
|
|
|
|
var replacement = ",".allMatches(trimmedString).length > 1 ? ", и" : " и";
|
2022-03-01 10:30:23 +03:00
|
|
|
|
|
|
|
|
|
return trimmedString.replaceRange(lastComma, lastComma + 1, replacement);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-03-29 09:52:34 +03:00
|
|
|
|
class PremiumCoffeDecorator implements Beverage {
|
2022-03-01 10:30:23 +03:00
|
|
|
|
Beverage _coffee = Coffee();
|
|
|
|
|
double get cost => _coffee.cost * 5;
|
|
|
|
|
String get ingredients => _coffee.ingredients;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
void main() {
|
|
|
|
|
var coffee = Coffee();
|
2022-03-29 09:52:34 +03:00
|
|
|
|
var premCoffee = PremiumCoffeDecorator();
|
2022-03-01 10:30:23 +03:00
|
|
|
|
|
2022-03-29 09:52:34 +03:00
|
|
|
|
print(
|
|
|
|
|
"Обычное кофе состоит из ${coffee.ingredients}. Оно стоит \$${coffee.cost}");
|
|
|
|
|
print(
|
|
|
|
|
"Лучшее кофе состоит из ${premCoffee.ingredients}. Оно стоит \$${premCoffee.cost}");
|
2022-03-01 10:30:23 +03:00
|
|
|
|
|
|
|
|
|
// Coffee contains coffee, milk, and sugar. It costs $0.85
|
|
|
|
|
// Starbucks coffee contains coffee, milk, and sugar. It costs $4.25
|
|
|
|
|
}
|