CS 210 Introduction to Design Patterns September 12 th, 2006.
-
Upload
katherine-chambers -
Category
Documents
-
view
220 -
download
4
Transcript of CS 210 Introduction to Design Patterns September 12 th, 2006.
A coffee shop example…
Beverage
description
getDescription()Cost()
DarkRoast
cost()
HouseBlend
cost()
Decaf
cost()
Espresso
cost()
What if you want to show the addition of condiments such as steamed milk, soy, mocha and whipped milk?
Potential problems with the design so far?
Solution is not easily extendable• How to deal with
• new condiments
• Price changes
• New beverages that may have a different set of condiments – a smoothie?
• Double helpings of condiments
Design Principle
The Open-Closed Principle
Classes should be open for extension, but closed for modification.
The Decorator Pattern
Take a coffee beverage object – say DarkRoast object
Decorate it with Mocha Decorate it with Whip Call the cost method and rely on
delegation to correctly compute the composite cost
Decorator Pattern
The decorator pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality.
Starbuzz code
public abstract class Beverage {String description = "Unknown Beverage";
public String getDescription() {
return description;}
public abstract double cost();
}
Decorator Class
public abstract class CondimentDecorator extends Beverage {
public abstract String getDescription();
}
Coding Bevarages
public class Espresso extends Beverage {
public Espresso() {description = "Espresso";
}
public double cost() {return 1.99;
}}
Another beverage
public class DarkRoast extends Beverage {public DarkRoast() {
description = "Dark Roast Coffee";}
public double cost() {
return .99;}
}
Coding Condimentspublic class Mocha extends CondimentDecorator {
Beverage beverage;
public Mocha(Beverage beverage) {this.beverage = beverage;
}
public String getDescription() {return beverage.getDescription() + ", Mocha";
}
public double cost() {return .20 + beverage.cost();
}}
Serving some coffee – Espresso please
public class StarbuzzCoffee {
public static void main(String args[]) {Beverage beverage = new Espresso();System.out.println(beverage.getDescription()
+ " $" + beverage.cost());
How about a double mocha dark roast with whipped milk?
Beverage beverage2 = new DarkRoast();beverage2 = new Mocha(beverage2);beverage2 = new Mocha(beverage2);beverage2 = new Whip(beverage2);
System.out.println(beverage2.getDescription() + " $" + beverage2.cost());
House blend with soy, mocha and whip, please
Beverage beverage3 = new HouseBlend();beverage3 = new Soy(beverage3);beverage3 = new Mocha(beverage3);beverage3 = new Whip(beverage3);System.out.println(beverage3.getDescription()
+ " $" + beverage3.cost());}
}