I'm making the very common example of Factory design pattern which creates a factory of shapes and return an instance of the type Shape. I wonder which is the best way to replace that bunch of nested if-else statements so that my code is more readable and maintainable.
I think there should exist a suitable design pattern to solve this issue but since I'm a beginner using design patterns I don't know where to start.
This is the code snippet for the getShape()
method:
public Shape getShape(String type, String scope) {
if (type == null) {
return null;
}
if (type.equalsIgnoreCase("circle")) {
if (scope.equalsIgnoreCase("singleton")) {
return SingletonCircle.getInstance();
}
return new PrototypeCircle();
} else if (type.equalsIgnoreCase("rectangle")) {
if (scope.equalsIgnoreCase("singleton")) {
return SingletonRectangle.getInstance();
}
return new PrototypeRectangle();
} else if (type.equalsIgnoreCase("square")) {
if (scope.equalsIgnoreCase("singleton")) {
return SingletonSquare.getInstance();
}
return new PrototypeSquare();
}
return null;
}