Decorator Design Pattern

A simple example of the decorator design pattern in Java.
This is very popular example (and very illustrative) of the Pizza Shop.

Create a Pizza Interface.

We will create a concrete PlainPizza in a second, by implementing this interface.

1
2
3
4
5
6
interface Pizza {

String getDescription();

double getPrice();
}

Concrete PlainPizza class.

We are giving some default values to our Plain Pizza which will be dressed with the toppings.

1
2
3
4
5
6
7
8
9
10
class PlainPizza implements Pizza {

public String getDescription() {
return "Plain Pizza";
}

public double getPrice() {
return 3.00;
}
}

Create a Topping abstract class.

It implements Pizza as well, and HAS-A pizza; This will enable Toppings to be wrapped around each other.
This is our Decorator.

1
2
3
4
5
6
7
8
9
10
11
12
abstract class Topping implements Pizza {

protected Pizza pizza;

Topping(Pizza pizza) {
this.pizza = pizza;
}

abstract public String getDescription();

abstract public double getPrice();
}

Create a CheeseTopping class

Our first topping type. We are using pizza instance we defined in Decorator, and adding extra values.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class CheeseTopping extends Topping {

CheeseTopping(Pizza pizza) {
super(pizza);
}

public String getDescription() {
return pizza.getDescription() +
", added Cheese";
}

public double getPrice() {
return pizza.getPrice() + 0.50;
}
}

Create a PepperoniTopping class

Our second topping type. Obviously, we can add as many as we like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class PepperoniTopping extends Topping {

PepperoniTopping(Pizza pizza) {
super(pizza);
}

public String getDescription() {
return pizza.getDescription() +
", added Pepperoni";
}

public double getPrice() {
return pizza.getPrice() + 0.30;
}
}

Create your client

An actual user of your pizza Decorator. You can see how Decorators are wrapping Pizzas and other decorators.

1
2
3
4
5
6
7
8
9
10
class Main {

public static void main(String[] args) {

Pizza pizza = new PepperoniTopping(new CheeseTopping(new PlainPizza()));

System.out.println("Description: " + pizza.getDescription());
System.out.println("Price: " + pizza.getPrice());
}
}

Run it on repl.it:
https://repl.it/@NenadP/Decorator-pattern-example#Main.java

UML Diagram for our Pizza Decorator pattern example:

Github example:
https://github.com/NenadP/super-simple-coding/tree/master/src/designpatterns/decorator

Wikipedia:
https://en.wikipedia.org/wiki/Decorator_pattern#cite_note-1