Design Patterns Java™ Workbook

(Michael S) #1
Chapter 27. Decorator

The constructor for the Abs class collaborates with its superclass to store a source function in
source[0].


The f() method of class Abs shows DECORATOR at work. This method applies an absolute-
value function to the value of another function at the given time. In other words, the
Abs.f() method decorates its source function with an absolute-value function. This simple
idea lets us compose an infinite number of functions from a small hierarchy of classes. The
code for the Cos and Sin classes is almost identical to the code for the Abs class.


The T class provides a trivial identity function:


package com.oozinoz.function;
public class T extends Function
{
public T()
{
super(new Function[0]);
}
public double f(double t)
{
return t;
}
}


The T class lets you model functions that vary linearly with time. For example, in the
ShowFunZone class, the arc of a circle varies from 0 to 2 times pi as time varies from 0 to 1:


Function theta = new Arithmetic(
'',
new Constant(2
Math.PI),
new T());


The Constant class represents a value that does not change over time:


package com.oozinoz.function;
public class Constant extends Function
{
private double constant;
public Constant(double constant)
{
super(new Function[0]);
this.constant = constant;
}
public double f(double t)
{
return constant;
}
}


The Arithmetic class requires an operator and two Function arguments:

Free download pdf