Design Patterns Java™ Workbook

(Michael S) #1
Chapter 27. Decorator

package com.oozinoz.function;
public class Arithmetic extends Function
{
protected char operator;


public Arithmetic(
char operator,
Function f1,
Function f2)
{
super(new Function[] { f1, f2 });
this.operator = operator;
}


public double f(double t)
{
switch (operator)
{
case '+' :
return source[0].f(t) + source[1].f(t);
case '-' :
return source[0].f(t) - source[1].f(t);
case '' :
return source[0].f(t)
source[1].f(t);
case '/' :
return source[0].f(t) / source[1].f(t);
default :
return 0;
}
}
}


CHALLENGE 27.3


Write the code for an Exp class that wraps Math.exp() around its source function.

Suppose that the brightness of a star is a sine wave that decreases exponentially:


As before, a plot of brightness versus time requires no new classes:


package com.oozinoz.applications;
import com.oozinoz.function.*;
public class ShowBrightness
{
public static void main(String args[])
{
FunPanel p = new FunPanel();
p.setPreferredSize(
new java.awt.Dimension(200, 200));

Free download pdf