Factory in Java when concrete objects take different constructor parameters

Jjang picture Jjang · Dec 14, 2012 · Viewed 28.3k times · Source

I'm trying to implement a Factory pattern in Java. I have a class called Shape which Circle and Triangle extends. The problem is that Shape constructor gets only 2 parameters while Circle gets 3 parameters and so is Triangle (which I won't show in the code section because is identical to Circle). To demonstrate it better:

    private interface ShapeFactory{
        public Shape create(int x, int y);
    }

    private class CircleFactory implements ShapeFactory{
        public Shape create(float radius, int x, int y){ //error
            return new Circle(radius, x,y);
        }
    }

Any ideas how to overcome this problem? I must not recieve an input from user inside the factory (must be recieved from outside).

Thanks!

Answer

Random42 picture Random42 · Dec 14, 2012

You have two options:

1) Abstract Factory:

RectangularShape extends Shape

RoundShape extends Shape

and RectangularShapeFactory and RoundShapeFactory

2) Builder (see also Item 2 in Effective Java)

public Shape {
    private final int x;
    private final int y;
    private final double radius;

    private Shape(Builder builder) {
        x = builder.x;
        y = builder.y;
        radius = builder.radius;
    }

    public static class Builder {
        private final int x;
        private final int y;
        private double radius;

        public Builder(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public Builder radius(double radius) {
            this.radius = radius;
            return this;
        }

        public Shape build() {
            return new Shape(this);
        }    
    }
}

//in client code 

    Shape rectangle = new Shape.Builder(x,y).build();
    Shape circle = new Shape.Builder(x,y).radius(radiusValue).build();