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

  1. Decorator wraps original object
  2. Each decorator adds to result
  3. Chain decorators together

Related Inheritance exercises

Practice all Inheritance exercises · Run this idea in the Java compiler