You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
36 lines
1.4 KiB
36 lines
1.4 KiB
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()
|
|
);
|
|
}
|
|
} |