Simple Decorator in Java: Explanation & Practice
Add functionality using decorator
Problem summary
Create Coffee with decorators (Milk, Sugar) that add to price.
Starter code
// Coffee interface: double getPrice(), String getDescription()
// SimpleCoffee: base price 5
// MilkDecorator: adds 2
// SugarDecorator: adds 1
public class Main {
public static void main(String[] args) {
// Coffee with milk and sugar
// Print: <description>: lt;price>
}
}Expected output and test cases
- Full order
Coffee, Milk, Sugar: $8.0
- Coffee with milk
Coffee, Milk: $7.0
- Plain coffee
Coffee: $5.0
Hints
- Decorator wraps original object
- Each decorator adds to result
- Chain decorators together
Related Inheritance exercises
- Practice Template Method Pattern in Java
- Practice Simple Factory Pattern in Java
- Practice Media Library System in Java
Practice all Inheritance exercises · Run this idea in the Java compiler