Low-Level Design (LLD)
PatternsStructural Patterns·1 min revision·Updated 2026-10-29

Decorator Pattern

Decorator Pattern = add behavior to object dynamically by wrapping it, without changing original class.

#LLD#Patterns#Java#Decorator Pattern
1-Minute Revision Card
Decorator Pattern
Core Entities & Components
DecoratorFactoryDecoratorInterfaceConcreteProduct
Architecture & Patterns
Decorator Pattern
Key Methods, APIs & Formulas
create()getInstance()process()
Exact Phrases to Say in the Interview
  • “I will apply Decorator Pattern here to encapsulate changes and satisfy Open/Closed principle.”
  • “De-couples core execution from specific implementations.”

Decorator Pattern

1. Meaning

Decorator Pattern = add behavior to object dynamically by wrapping it, without changing original class.

2. Real-life example

Coffee shop:

  • Basic coffee → ₹100.
  • Add milk → ₹120.
  • Add milk + caramel → ₹150.

Each decorator adds cost and behavior around existing coffee.

3. Tiny bad code vs good code

Bad: subclass explosion

Java

java
class Coffee {}
class MilkCoffee extends Coffee {}
class CaramelCoffee extends Coffee {}
class MilkCaramelCoffee extends Coffee {}

Problem: every combination → another subclass.

Good: Decorator Pattern

Java

java
interface Coffee {
    String description();
    double cost();
}

class BasicCoffee implements Coffee {
    public String description() {
        return "Coffee";
    }

    public double cost() {
        return 100;
    }
}

abstract class CoffeeDecorator implements Coffee {
    protected final Coffee coffee;

    CoffeeDecorator(Coffee coffee) {
        this.coffee = coffee;
    }
}

class MilkDecorator extends CoffeeDecorator {
    MilkDecorator(Coffee coffee) {
        super(coffee);
    }

    public String description() {
        return coffee.description() + " + Milk";
    }

    public double cost() {
        return coffee.cost() + 20;
    }
}

class CaramelDecorator extends CoffeeDecorator {
    CaramelDecorator(Coffee coffee) {
        super(coffee);
    }

    public String description() {
        return coffee.description() + " + Caramel";
    }

    public double cost() {
        return coffee.cost() + 30;
    }
}

class Main {
    public static void main(String[] args) {
        Coffee coffee = new CaramelDecorator(
            new MilkDecorator(new BasicCoffee())
        );

        System.out.println(coffee.description());
        System.out.println(coffee.cost());
    }
}

Output:

Coffee + Milk + Caramel
150.0

How wrapping works:

BasicCoffee

Abhinandan Mishra

SDE-II · Distributed Systems · Developer Tools

© 2026 Abhinandan Mishra

Built with Next.js & Tailwind CSS

abhinandanmishra360@gmail.com