SE450: Factory: Polymorphic Factory Method [30/32] Previous pageContentsNext page

The object created depends upon the actual type of the creator.

This is called Factory Method by GoF.

The polymorphic factory method pattern is used to connect two hierarchies. A good example is java.util.Collection and java.util.Iterator.

Here is a silly example, using triples rather than general collections:

file:Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
package factory.factorymethod;
public class Main {
  public static void main (String[] args) {
    Triple<String> t1 = new FieldTriple<String>("dog", "cat", "pig");
    Triple<String> t2 = new ArrayTriple<String>("daisy", "rose", "tulip");
    for (String s : t1)
      System.out.println(s);
    for (String s : t2)
      System.out.println(s);
  }
}

file:Triple.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package factory.factorymethod;
import java.util.Iterator;
import java.util.ArrayList;
interface Triple<E> extends Iterable<E> { }
class FieldTriple<E> implements Triple<E> {
  private E one; E two; E three;
  public FieldTriple(E one, E two, E three) {
    this.one = one; this.two = two; this.three = three;
  }
  public Iterator<E> iterator() { return new TheIterator(); }

  private class TheIterator implements Iterator<E> {
    private int i;
    public boolean hasNext() { return i < 3; }
    public E next() {
      i++;
      switch (i) {
      case 1: return one;
      case 2: return two;
      case 3: return three;
      }
      throw new java.util.NoSuchElementException();
    }
    public void remove() { throw new UnsupportedOperationException(); }
  }
}
// Arrays do not play nicely with generics, so use ArrayList
class ArrayTriple<E> implements Triple<E> {
  private ArrayList<E> a = new ArrayList<E>();
  public ArrayTriple(E one, E two, E three) {
    a.add(0,one); a.add(1,two); a.add(2,three);
  }
  public Iterator<E> iterator() { return new TheIterator(); }

  private class TheIterator implements Iterator<E> {
    private int i = -1;
    public boolean hasNext() { return i < 2; }
    public E next() {
      i++;
      if (i <= 2)
        return a.get(i);
      else
        throw new java.util.NoSuchElementException();
    }
    public void remove() { throw new UnsupportedOperationException(); }
  }
}

Previous pageContentsNext page