There are three different types of Shapes: Rectangle, Circle, Triangle
These shapes share some code which is placed in the parent (Shape), and there is one method that is implemented differently across these three shapes: draw()
Based on the input value, one of the three implementations of that method gets called:
abstract class Shape {
@Autowired
private Rectangle rectangle;
@Autowired
private Circle circle;
@Autowired
private Triangle triangle;
public String drawIt(ShapeEnum shape, String param1, String param2) {
switch(shape) {
case ShapeEnum.Rectangle:
return rectangle.draw();
case ShapeEnum.Circle:
return circle.draw();
case ShapeEnum.Triangle:
return triangle.draw();
}
}
protected int sharedMethod1() {//....}
protected int sharedMethod2() { //...}
protected abstract String draw();
}
@Controller
public class Controller {
@Autowired
private Shape shape;
@RequestMapping(path = "", method = RequestMethod.POST)
public String getDrawing(@RequestBody GetShapeRequest shapeRequest) {
return shape.drawIt(ShapeEnum.valueOf(shapeRequest), shapeRequest.getParam1(), shapeRequest.getParam2());
}
}
Obviously this doesn't work, because Spring cannot instantiate an abstract class that has three children. I'm wondering how I should implement it then? Is there a way to have one parent at the top deciding which child to call? or should I wire in all three children in the controller? I really don't like this idea because I'm going to add tens of other shapes and I prefer to control the flow in Shape rather in controller.
Aucun commentaire:
Enregistrer un commentaire