174. Implementing the Decorator pattern

The Decorator pattern prefers composition over inheritance; therefore, it is an elegant alternative to the subclassing technique. With this, we mainly start from a base object and add additional features in a dynamic fashion.

For example, we can use this pattern to decorate a cake. The decoration process doesn't change the cake itself – it just adds some nuts, cream, fruit, and so on.

The following diagram illustrates what we will implement:

First, we create an interface called Cake:

public interface Cake { String decorate();}

Then, we implement this interface via BaseCake:

public class BaseCake implements ...

Get Java Coding Problems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.