Decorator design pattern allows you to add new features or behaviors to an object dynamically, without changing its core structure. It’s like putting layers on top of an object to enhance its functionality.
5 real world example of Decorator Design Pattern
Coffee ordering system (customizing coffee with toppings and flavors)
Vehicle customization services (adding features to vehicles)
Cake decoration in bakeries (enhancing cake appearance)
Pizza customization (adding toppings to a base pizza)
Video game character customization (adding clothing, weapons, or accessories to characters)
Design Principle
Classes should be open for extension, but closed for modification.
Class Disgram

Without Decorator Design Pattern
public class Car {
private String model;
private double basePrice;
public Car(String model, double basePrice) {
this.model = model;
this.basePrice = basePrice;
}
public double getPrice(){
return basePrice;
}
}
public class Main {
public static void main(String[] args) {
Car baseCar = new Car("Basic Car", 20000.0);
System.out.println("Basic Car Price: "+ baseCar.getPrice());
double carWithLeatherSeatPrice = baseCar.getPrice()+1000.0;
System.out.println("Car with Leather Seat Price: "+ carWithLeatherSeatPrice);
double carWithLeatherSeatAndSunRoof = baseCar.getPrice()+1000.0+ 500.0;
System.out.println("Car with leather Seat and Sunroof Price: "+ carWithLeatherSeatAndSunRoof);
}
}
With Decorator Design Pattern
public interface Car {
double getPrice();
}
public class BasicCar implements Car{
private String model;
private double basePrice;
public BasicCar(String model, double basePrice) {
this.model = model;
this.basePrice = basePrice;
}
@Override
public double getPrice() {
return basePrice;
}
}
public class CarDecorator implements Car{
protected Car decoratedCar;
public CarDecorator(Car decoratedCar) {
this.decoratedCar = decoratedCar;
}
@Override
public double getPrice() {
return decoratedCar.getPrice();
}
}
public class LeatherSeatDecorator extends CarDecorator{
public LeatherSeatDecorator(Car decoratedCar) {
super(decoratedCar);
}
@Override
public double getPrice() {
return super.getPrice()+1000.0;
}
}
public class SunRoofDecorator extends CarDecorator{
public SunRoofDecorator(Car decoratedCar) {
super(decoratedCar);
}
@Override
public double getPrice() {
return super.getPrice()+500.0;
}
}
public class Main {
public static void main(String[] args) {
Car basicCar = new BasicCar("Basic Car", 20000.0);
System.out.println("Basic Car Price: "+ basicCar.getPrice());
Car carWithLeatherSeats = new LeatherSeatDecorator(basicCar);
System.out.println("Car With Leather Seat: " + carWithLeatherSeats.getPrice());
Car carWithLeatherSeatsAndSunRoof = new SunRoofDecorator(carWithLeatherSeats);
System.out.println("Car with Leather Seat and SunRoof: "+ carWithLeatherSeatsAndSunRoof.getPrice());
}
}