Decorator Design Pattern

Go back

Aliases πŸ“Œ: None

Description πŸ“š: A decorator is a class that uses a concrete instance to delegate the implementation of an interface while using its own implementation for one or more methods.

Advantages βœ…

  • Avoid using inheritance slots (ex: extends in Java)

Disadvantages 🚫

  • ???

Notes πŸ“

  • An alternative to inheritance

Java implementation

public interface Food {
    String getName();
    int getPrice();

    default String print() {
        return "{ name:" + getName() + ", price:" + getPrice() + " }";
    }
}
public class Pizza implements Food {
    @Override
    public String getName() {
        return "Pizza";
    }

    @Override
    public int getPrice() {
        return 7;
    }
}
public class DriveFood implements Food {
    private final Food decorated;

    public DriveFood(Food food) {
        this.decorated = decorated;
    }

    @Override
    public int getPrice() {
        // increase the price
        return decorated.getPrice() + 3;
    }

    @Override
    public String getName() {
        return decorated.getName();
    }
}
public class Main {
    public static void main(String[] args) {
        Pizza p = new Pizza();
        System.out.println(p.print()); // { name:Pizza, price:7 }
        DriveFood f = new DriveFood(p);
        System.out.println(f.print()); // { name:Pizza, price:10 }
    }
}