Professional Documents
Culture Documents
Decorator Pattern Part 2: Implementation
Decorator Pattern Part 2: Implementation
Decorator Pattern Part 2: Implementation
Implementation
Recap
Coffee Shop Ordering System Example
First Design
i o n
lo s
exp
s s
Cl a
Coffee Shop Design 2
rclass
upe
es
t h
l i t y in ate
t i o na opri asses
c r l
d fun ot app e subc
Ad t is n of th
tion
tha some f i ca
for mod i
l e for
b
n f l exi
I
Recap
• We had two designs, where inheritance was used to inherit behaviors
• The first design issue: too many classes (class explosion)
• The second design issue: Subclasses inherit functionality not
appropriate for them
• Both share common thing:
• inflexible design, adding functionality to cope with new requirement,
require modifying the code
Design Principle: Classes should be open for extension, but closed for modification
Goal
• is to be able to add functionalities to an object (decorate the object)
dynamically at runtime
• extend the code without modifying it
• in the coffee shop ordering system
• customer start with main beverage and decorate it with condiment(s)
dynamically
• without the need to have all possible combinations between main beverages
& condiments at compile time
Decorator Pattern Definition
concrete components
decorator
concrete decorators
Apply Decorator on the Coffee Shop
Ordering System
abstract component
concrete components
decorator
concrete decorators
Inheritance & Composition
• The decorator (CondimentDecorator) has two relation with the
component (Beverage)
• It is extending the Beverage (inheritance)
• this is to make sure that decorator is of the same type as the
component it is decorating (type matching)
• inheriting the type, not the behavior
• Is is holding a reference to it (composition)
• to get the behavior
Inheritance vs. Composition
• Adding new behavior
• with inheritance we need to modify the code of superclass
• with composition we can implement new decorator with out modifying the
code of super class
Implementation
Beverage Class
• Abstract class
concrete components
Concrete Components
• Extends the superclass (Beverage)
• Set the description in the constructor public class Espresso extends Beverage {
public class Decaf extends Beverage { public class DarkRoast extends Beverage {
public Decaf() { public DarkRoast() {
description = "Decaf Coffee"; description = "Dark Roast Coffee";
} }
decorator
concrete decorators
Concrete Decorator (Type of Condiments)
public class Mocha extends CondimentDecorator {
• Extends the main decorator (condiment Beverage beverage;
decorator)
System.out.println(beverage2.getDescription()
+ " $" + beverage2.cost());
}
}