Decorator Pattern 1 Decorator Pattern Can you say

  • Slides: 8
Download presentation
Decorator Pattern 1

Decorator Pattern 1

Decorator Pattern Can you say “composition” and “delegation”? Again? ? ? 2

Decorator Pattern Can you say “composition” and “delegation”? Again? ? ? 2

Decorator Pattern - Problem Want to allow adding new behaviors to an object without

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 fly Flags in Beverage? Many combos are nonsense Have to modify Beverage to add new options Tea: Options make sense? Clothing another example Take off jacket? Put on hat? 2 flags or 4 classes? No! How do w/o mod’ing existing classes? 3

Decorator - Solution By composing and delegating, Condiments are “decorating” the cost and description

Decorator - Solution By composing and delegating, Condiments are “decorating” the cost and description 4

UML for Coffee Decorator Composes (HAS-A) Extends 5

UML for Coffee Decorator Composes (HAS-A) Extends 5

UML for Decorator In family of patterns called “Wrapper” 6

UML for Decorator In family of patterns called “Wrapper” 6

Code a Capitalization Decorator Example: hello earthlings Hello Earthlings class Word. Reader extends Reader

Code a Capitalization Decorator Example: hello earthlings Hello Earthlings class Word. Reader extends Reader { public Word. Reader (File file); public int read (char[] cbuf); // cbuf holds word } You are decorating the Word. Reader class (or rather, it’s objects) with the capitalization capability. Nesting (composing) a Word. Reader inside Capitalization. Decorator Useful resource: static char Character. to. Upper. Case(char) 7

Capitalization Decorator class Word. Reader extends Reader { public Word. Reader (File file); public

Capitalization Decorator class Word. Reader extends Reader { public Word. Reader (File file); public int read (char[] cbuf); // cbuf holds word } class Upper. Reader. Decorator extends Reader. Decorator { Reader inner. Reader; public Upper. Reader. Decorator(Reader i. R) { inner. Reader = i. R; } public int read (char[] cbuf) { int length = inner. Reader. read(cbuf); cbuf[0] = Character. to. Upper. Case(cbuf[0]); return length; abstract class Reader. Decorator extends Reader { } abstract public int read (char[] cbuf); } } char[100] mybuf; Reader myreader = new Word. Reader(System. in); myreader = new Upper. Reader. Decorator(myreader); int length = myreader. read(mybuf); 8