SE450: Template Method: Using Subclassing (Template) [25/35] Previous pageContentsNext page

file:template/series4/Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package template.series4;

interface Series {
  void next();
  void print();
}
class SeriesFactory {
  private SeriesFactory() {}
  public static Series newArith() { return new ArithSeries(); }
  public static Series newGeom()  { return new GeomSeries(); }
}
abstract class AbstractSeries implements Series {
  int x;
  int y = 1;
  public void next()  { x++; y = this.eval(y,2); }
  public void print() { System.out.println("x=" + x + "; y=" + y); }

  abstract protected int eval(int x, int y);
}

class ArithSeries extends AbstractSeries { protected int eval(int x, int y) { return x+y; } }
class GeomSeries extends AbstractSeries { protected int eval(int x, int y) { return x*y; } }

public class Main {
  public static void main(String[] args) {
    Series x = SeriesFactory.newGeom();
    x.next();
    x.next();
    x.print();
  }
}

Previous pageContentsNext page