Can you say composition and delegation Again 2 Decorator Pattern Problem Want to allow adding new behaviors to an object without modifying class Coffee condiments example is great ID: 628103
Download Presentation The PPT/PDF document "Decorator Pattern 1 Decorator Pattern" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Decorator Pattern
1Slide2
Decorator Pattern
Can you say “composition” and “delegation”? Again???
2Slide3
Decorator Pattern - Problem
Want to allow
adding new behaviors
to an object
without modifying
class
Coffee condiments example is great
Soy, Mocha, Whip, …
Class for each combination?
2
n is too many!And would be static –cannot change on the flyFlags in Beverage?Many combos are nonsenseHave to modify Beverage toadd new optionsClothing another exampleTake off jacket?Put on hat?2 flags or 4 classes? No!How do w/o mod’ing existing classes?
3
Tea: Options make sense?Slide4
Decorator - Solution
4
By
composing
and
delegating
, Condiments are “decorating” the cost and descriptionSlide5
UML for Coffee Decorator
5
Composes
(HAS-A)
ExtendsSlide6
UML for Decorator
6
In family of patterns called “Wrapper”Slide7
Code a Capitalization Decorator
Example:
hello earthlings Hello Earthlings
class
WordReader
extends Reader {
public
WordReader
(File file);
public
int read (char[]
cbuf); //
cbuf holds word}You are decorating
the
WordReader
class (or rather, it’s objects) with the
capitalization capability
.
7
Useful resource:
static char
Character.toUpperCase(char)
Nesting (composing) a WordReader inside CapitalizationDecoratorSlide8
Capitalization Decorator
class WordReader extends Reader {
public WordReader (File file); public int
read (char[]
cbuf
); //
cbuf
holds word
}
class
UpperReaderDecorator extends ReaderDecorator { Reader innerReader; public UpperReaderDecorator(Reader iR) { innerReader = iR;
} public int read (char[] cbuf) {
int length = innerReader.read(cbuf); cbuf[0] = Character.toUpperCase(cbuf[0]);
return length;
}
}
char[100]
mybuf
;
Reader
myreader = new WordReader(System.in);myreader = new
UpperReaderDecorator(myreader);int length = myreader.read(mybuf);
8
abstract class ReaderDecorator extends Reader { abstract public int read (char[] cbuf);}