Design Patterns Java™ Workbook

(Michael S) #1
Chapter 27. Decorator

import java.io.*;
public class LowerCaseFilter extends OozinozFilter
{
protected LowerCaseFilter(Writer out)
{
super(out);
}
public void write(int c) throws IOException
{
out.write(Character.toLowerCase((char) c));
}
}


The code for the TitleCaseFilter class is a bit more complex, as it has to keep track of
whether the stream is in whitespace:


import java.io.*;
public class TitleCaseFilter extends OozinozFilter
{
boolean inWhite = true;
protected TitleCaseFilter(Writer out)
{
super(out);
}


public void write(int c) throws IOException
{
out.write(
inWhite
? Character.toUpperCase((char) c)
: Character.toLowerCase((char) c));
inWhite = Character.isWhitespace((char) c) ||
c == '"';
}
}


CHALLENGE 27.2


Write the code for RandomCaseFilter.java.

Input and output streams provide a classic example of how the DECORATOR pattern lets you
assemble the behavior of an object at runtime. Another important application of DECORATOR
occurs when you need to create mathematical functions at runtime.


Function Decorators..................................................................................................................................


You can combine DECORATOR with the idea of treating functions as objects to allow for
runtime composition of new functions. In Chapter 4, Facade, you refactored an application
that shows the flight path of a nonexploding aerial shell. The original code calculated the path
in the paintComponent() method of a JPanel subclass:

Free download pdf