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!
You have two options:
1) Abstract Factory:
RectangularShape extends ShapeRoundShape extends Shapeand
RectangularShapeFactoryandRoundShapeFactory2) Builder (see also Item 2 in Effective Java)