SE450: Factory: Static Factory Method [10/16] Previous pageContentsNext page

A factory allows the concrete class names to remain hidden.

file:Shape.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
package factory.shape2;
import java.awt.Graphics;
public interface Shape {
  void paint(Graphics g);
}
class Circle implements Shape {
  public void paint(Graphics g) { /* ... */ }
  // ...
}
class Square implements Shape {
  public void paint(Graphics g) { /* ... */ }
  // ...
}

file:ShapeFactory.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
package factory.shape2;
public class ShapeFactory {
  private ShapeFactory() {}
  static public Shape newInstance(String selector) {
    if ("Circle".equals(selector)) return new Circle();
    if ("Square".equals(selector)) return new Square();
    throw new IllegalArgumentException();
  }
}

file:Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
package factory.shape2.main;
import factory.shape2.Shape;
import factory.shape2.ShapeFactory;
public class Main {
  public static void main (String[] args) {
    Shape[] a = new Shape[2];
    a[0] = ShapeFactory.newInstance("Circle");
    a[1] = ShapeFactory.newInstance("Square");
  }
}

Previous pageContentsNext page