lundi 16 mai 2016

How to handle interacting decorators

Given the classic coffee decorator example (copied from Wikipedia).

public interface Coffee {
    public double getCost();
}

public class SimpleCoffee implements Coffee {
    public double getCost() {
        return 1;
    }
}

public abstract class CoffeeDecorator implements Coffee {
    protected final Coffee decoratedCoffee;
    public CoffeeDecorator(Coffee c) {
        this.decoratedCoffee = c;
    }
    public double getCost() {
        return decoratedCoffee.getCost();
    }
}

class WithMilk extends CoffeeDecorator {
    public WithMilk(Coffee c) {
        super(c);
    }
    public double getCost() {
        return super.getCost() + MILKCOST;
    }
    public int someAttribute;
}

class WithMocha extends CoffeeDecorator {
    public WithMocha(Coffee c) {
        super(c);
    }
    public double getCost() {
        return super.getCost() + MOCHACOST;
    }
}

Suppose I want my WithMocha cost to use someAttribute if the WithMilk decorator exists, how would one design such a decorator system?

Is the decorator pattern even the best approach?

Aucun commentaire:

Enregistrer un commentaire