parent
86594d80ac
commit
1743f34cd5
@ -0,0 +1,36 @@
|
||||
package tiaozhanti;
|
||||
|
||||
import jichuti.Circle;
|
||||
import jichuti.Square;
|
||||
|
||||
public class BasicShapeConverter implements ShapeConverter {
|
||||
@Override
|
||||
public Shape convert(Shape source, Class<? extends Shape> targetType) {
|
||||
// 圆形 → 椭圆形(保持面积相等)
|
||||
if (source instanceof Circle && targetType == Oval.class) {
|
||||
Circle circle = (Circle) source;
|
||||
double radius = circle.getRadius();
|
||||
return new Oval(circle.getColor(), radius, radius); // 椭圆退化为圆形
|
||||
}
|
||||
|
||||
// 椭圆形 → 圆形(保持面积相等)
|
||||
if (source instanceof Oval && targetType == Circle.class) {
|
||||
Oval oval = (Oval) source;
|
||||
double area = oval.getArea();
|
||||
double radius = Math.sqrt(area / Math.PI); // 从面积反推半径
|
||||
return (Shape) new Circle(oval.getColor(), radius);
|
||||
}
|
||||
|
||||
// 正方形 → 圆形(保持面积相等)
|
||||
if (source instanceof Square && targetType == Circle.class) {
|
||||
Square square = (Square) source;
|
||||
double area = square.getArea();
|
||||
double radius = Math.sqrt(area / Math.PI);
|
||||
return (Shape) new Circle(square.getColor(), radius);
|
||||
}
|
||||
|
||||
throw new UnsupportedOperationException(
|
||||
"不支持转换:" + source.getClass().getSimpleName() + " → " + targetType.getSimpleName()
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in new issue