Decorator Pattern
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 96 of 110.
The Decorator pattern lets you add new behaviors to objects dynamically by wrapping them in special objects called decorators. Unlike inheritance, which adds behavior at compile time, decorators attach additional responsibilities at runtime without modifying the original class.
The key idea is that both the original object and decorators implement the same interface.
A decorator wraps the original object, delegates to it, and adds its own behavior before or after:
abstract class Coffee {
String getDescription();
double getCost();
}
class SimpleCoffee implements Coffee {
@override
String getDescription() => 'Simple Coffee';
@override
double getCost() => 2.0;
}
class MilkDecorator implements Coffee {
final Coffee _coffee;
MilkDecorator(this._coffee);
@override
String getDescription() => '${_coffee.getDescription()}, Milk';
@override
double getCost() => _coffee.getCost() + 0.5;
}
class SugarDecorator implements Coffee {
final Coffee _coffee;
SugarDecorator(this._coffee);
@override
String getDescription() => '${_coffee.getDescription()}, Sugar';
@override
double getCost() => _coffee.getCost() + 0.2;
}
void main() {
Coffee coffee = SimpleCoffee();
coffee = MilkDecorator(coffee);
coffee = SugarDecorator(coffee);
print(coffee.getDescription()); // Simple Coffee, Milk, Sugar
print(coffee.getCost()); // 2.7
}Each decorator wraps the previous object and enhances it. You can stack multiple decorators in any combination, creating flexible behavior without creating a subclass for every possible combination. This pattern is ideal when you need to add features to objects without affecting other objects of the same class.
Challenge
EasyLet's build a pizza ordering system using the Decorator pattern! You'll create a base pizza that can be enhanced with various toppings, where each topping wraps the previous item and adds to both the description and the price.
You'll organize your code into two files:
pizza.dart: This file contains your pizza interface and all the decorator classes. Start with an abstract classPizzathat defines two methods:String getDescription()anddouble getPrice(). Then create aPlainPizzaclass that implementsPizza- it returnsPlain Pizzaas its description and costs8.0. Now build three decorator classes that each wrap aPizzaand enhance it:CheeseDecorator- adds, Cheeseto the description and1.5to the pricePepperoniDecorator- adds, Pepperonito the description and2.0to the priceMushroomDecorator- adds, Mushroomsto the description and1.25to the price
Pizza, accept aPizzain its constructor, and delegate to the wrapped pizza before adding its own contribution.main.dart: Import your pizza file and demonstrate how decorators stack to build a customized order. Start with aPlainPizza, then wrap it withCheeseDecorator, then wrap that withPepperoniDecorator, and finally wrap everything withMushroomDecorator. Print the final pizza's description, then printTotal: $followed by the price.
Notice how each decorator builds upon the previous one - you're creating a fully loaded pizza by stacking simple, single-responsibility decorators!
Expected output:
Plain Pizza, Cheese, Pepperoni, Mushrooms
Total: $12.75Cheat sheet
The Decorator pattern adds new behaviors to objects dynamically by wrapping them in decorator objects. Both the original object and decorators implement the same interface.
Key components:
- An abstract class or interface that defines the common methods
- A concrete class that implements the base functionality
- Decorator classes that wrap the original object and enhance it
Each decorator:
- Implements the same interface as the object it decorates
- Holds a reference to the wrapped object
- Delegates calls to the wrapped object
- Adds its own behavior before or after delegation
abstract class Coffee {
String getDescription();
double getCost();
}
class SimpleCoffee implements Coffee {
@override
String getDescription() => 'Simple Coffee';
@override
double getCost() => 2.0;
}
class MilkDecorator implements Coffee {
final Coffee _coffee;
MilkDecorator(this._coffee);
@override
String getDescription() => '${_coffee.getDescription()}, Milk';
@override
double getCost() => _coffee.getCost() + 0.5;
}
// Stack multiple decorators
Coffee coffee = SimpleCoffee();
coffee = MilkDecorator(coffee);
coffee = SugarDecorator(coffee);Decorators can be stacked in any combination, creating flexible behavior without creating subclasses for every possible combination.
Try it yourself
import 'pizza.dart';
void main() {
// TODO: Create a PlainPizza
// TODO: Wrap it with CheeseDecorator
// TODO: Wrap that with PepperoniDecorator
// TODO: Wrap everything with MushroomDecorator
// TODO: Print the final pizza's description
// TODO: Print "Total: $" followed by the price
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor12Async OOP
Futures & async/awaitStreams BasicsStream ControllersAsync ConstructorsAsync in Class MethodsRecap - Data Fetcher15Design Patterns Part 2
Command PatternAdapter PatternDecorator PatternTemplate Method PatternState PatternComposite PatternRepository Pattern