/java/

Decorator Design Pattern

2014-09-23 13:04:23

Main.java

package decorator;

public class Main {

    public static void main(String[] args) {

        Pizza pizza = new PizzaLarge();
        pizza = new Cheese(pizza);
        pizza = new Sausage(pizza);

        System.out.println(pizza.getIngredients());
        System.out.println(pizza.getPrice());
    }
}

Pizza.java

package decorator;

public abstract class Pizza {
    public abstract String getIngredients();
    public abstract double getPrice();
}

PizzaTop.java

package decorator;

public abstract class PizzaTop extends Pizza {

    protected Pizza pizza;

    public PizzaTop(Pizza pizza) {
        this.pizza = pizza;
    }
}

PizzaDough.java

package decorator;

public abstract class PizzaDough extends Pizza {

}

PizzaSmall.java

package decorator;

public class PizzaSmall extends PizzaDough {

    @Override
    public String getIngredients() {
        return "Pizza small";
    }

    @Override
    public double getPrice() {
        return 1;
    }
}

PizzaMedium.java

package decorator;

public class PizzaMedium extends PizzaDough {

    @Override
    public String getIngredients() {
        return "Pizza Medium";
    }

    @Override
    public double getPrice() {
        return 1.5;
    }
}

PizzaLarge.java

package decorator;

public class PizzaLarge extends PizzaDough {

    @Override
    public String getIngredients() {
        return "Pizza large";
    }

    @Override
    public double getPrice() {
        return 2;
    }
}

Cheese.java

package decorator;

public class Cheese extends PizzaTop {

    public Cheese(Pizza pizza) {
        super(pizza);
    }

    @Override
    public String getIngredients() {
        return pizza.getIngredients() + ", cheese";
    }

    @Override
    public double getPrice() {
        return pizza.getPrice() + 0.5;
    }
}

Sausage.java

package decorator;

public class Sausage extends PizzaTop {

    public Sausage(Pizza pizza) {
        super(pizza);
    }

    @Override
    public String getIngredients() {
        return pizza.getIngredients() + ", sausage";
    }

    @Override
    public double getPrice() {
        return pizza.getPrice() + 1.5;
    }
}