SE450: Factory: Static Factory Class [12/16] Previous pageContentsNext page

An alternative is to use multiple factory methods.

file:Shape.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
package factory.shape4;
import java.awt.Graphics;
public interface Shape {
  void paint(Graphics g);
}
class Ellipse implements Shape {
  Ellipse(int radius1, int radius2) { /* ... */ }
  public void paint(Graphics g) { /* ... */ }
  // ...
}
class Rectangle implements Shape {
  Rectangle(int height, int width) { /* ... */ }
  public void paint(Graphics g) { /* ... */ }
  // ...
}

file:ShapeFactory.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
package factory.shape4;
public class ShapeFactory {
  private ShapeFactory() {}
  static public Shape newEllipse(int radius1, int radius2) {
    return new Ellipse(radius1, radius2);
  }
  static public Shape newCircle(int radius) {
    return new Ellipse(radius, radius);
  }
  static public Shape newRectangle(int height, int width) {
    return new Rectangle(height, width);
  }
  static public Shape newSquare(int height) {
    return new Rectangle(height, height);
  }
}

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

Previous pageContentsNext page