SE450: Factory: Benefit [11/16] Previous pageContentsNext page

Changing names does not affect client code.

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

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

file:Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
package factory.shape3.main;
import factory.shape3.Shape;
import factory.shape3.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