Decorator Pattern in Java: Explanation & Practice

Implement the decorator design pattern

Problem summary

Create a Coffee interface and decorators to add Milk and Sugar, each adding to the cost.

Starter code

interface Coffee {
    double getCost();
    String getDescription();
}

// Implement SimpleCoffee, MilkDecorator, SugarDecorator

public class Main {
    public static void main(String[] args) {
        Coffee coffee = new SimpleCoffee();
        coffee = new MilkDecorator(coffee);
        coffee = new SugarDecorator(coffee);
        
        System.out.println(coffee.getDescription() + " quot; + coffee.getCost());
    }
}

Expected output and test cases

  • Decorators add to description and cost
    Simple Coffee, Milk, Sugar $2.0

Hints

  1. Decorators wrap a Coffee object
  2. Call wrapped object's methods
  3. Add decorator's contribution to result

Related OOP Basics exercises

Practice all OOP Basics exercises · Run this idea in the Java compiler