import javax.swing.JOptionPane; import java.text.NumberFormat; import java.util.Locale; //This example shows a combination of the decorator pattern and inheritance //It is an adaptation of an example of Bruce Eckel public class TestCoffeeShop1 { public TestCoffeeShop1() { DrinkItem aDrink; aDrink = new Cream(new Coffee()); display(aDrink); aDrink = new Coffee(); aDrink = new Cream(aDrink); aDrink = new Sugar(aDrink); aDrink = new Lemon(aDrink); display(aDrink); aDrink = new Cream(new Tea()); display(aDrink); aDrink = new Coffee(); display(aDrink); } // end TestCoffeeShop1 public void display(DrinkItem d) { NumberFormat money = NumberFormat.getCurrencyInstance(Locale.US); String out = "Your drink is " + d.getDescription(); out += "\nThe cost is " + money.format(d.getCost()); JOptionPane.showMessageDialog(null,out); } interface DrinkItem { public double getCost(); public String getDescription(); }// end DrinkItem class Coffee implements DrinkItem { public double getCost() { return 1.99; } public String getDescription() { return "Coffee "; } }// end Coffee class Tea implements DrinkItem { public double getCost() { return 1.49; } public String getDescription() { return "Tea "; } }// end Tea class Decorator implements DrinkItem { private DrinkItem drink; public Decorator(DrinkItem drink) { this.drink = drink; } public DrinkItem getDrinkItem() { return drink; } public double getCost() { return drink.getCost(); } public String getDescription() { return drink.getDescription(); } }// end Decorator class Cream extends Decorator { public Cream(DrinkItem d) { super(d); } public double getCost() { return getDrinkItem().getCost() + 0.25; } public String getDescription() { return getDrinkItem().getDescription() + "with cream "; } }// end Cream class Sugar extends Decorator { public Sugar(DrinkItem d) { super(d); } public double getCost() { return getDrinkItem().getCost() + 0.25; } public String getDescription() { return getDrinkItem().getDescription() + "with sugar "; } }// end Sugar class Lemon extends Decorator { public Lemon(DrinkItem d) { super(d); } public double getCost() { return getDrinkItem().getCost() + 0.10; } public String getDescription() { return getDrinkItem().getDescription() + "with lemon "; } }//end Lemon public static void main(String[] args) throws Exception { new TestCoffeeShop1(); System.exit(0); } } // end TestCoffeeShop