package challenge; import basic.Shape; import advanced.Resizable; import java.util.ArrayList; import java.util.List; /** * 复合图形类,实现Shape接口和Resizable接口,用于组合多个图形 */ public class CompositeShape implements Shape, Resizable { private String color; private String name; private List shapes; /** * 构造方法 * @param name 复合图形的名称 * @param color 复合图形的颜色 */ public CompositeShape(String name, String color) { this.name = name; this.color = color; this.shapes = new ArrayList<>(); } /** * 添加子图形 * @param shape 要添加的图形 */ public void addShape(Shape shape) { if (shape != null) { shapes.add(shape); } } /** * 移除子图形 * @param shape 要移除的图形 * @return 如果移除成功则返回true,否则返回false */ public boolean removeShape(Shape shape) { return shapes.remove(shape); } /** * 移除所有子图形 */ public void clearShapes() { shapes.clear(); } /** * 获取子图形列表 * @return 子图形列表 */ public List getShapes() { return new ArrayList<>(shapes); // 返回副本,防止外部修改 } @Override public String getColor() { return color; } @Override public double getArea() { double totalArea = 0.0; for (Shape shape : shapes) { totalArea += shape.getArea(); } return totalArea; } @Override public void display() { System.out.println("CompositeShape [name=" + name + ", color=" + color + ", totalShapes=" + shapes.size() + ", totalArea=" + getArea() + "]"); System.out.println(" 子图形列表:"); for (int i = 0; i < shapes.size(); i++) { System.out.print(" " + (i + 1) + ". "); shapes.get(i).display(); } } @Override public void enlarge(double factor) { if (factor > 0) { for (Shape shape : shapes) { if (shape instanceof Resizable) { ((Resizable) shape).enlarge(factor); } } } } @Override public void shrink(double factor) { if (factor > 0 && factor < 1) { for (Shape shape : shapes) { if (shape instanceof Resizable) { ((Resizable) shape).shrink(factor); } } } } @Override public String getSizeInfo() { return "CompositeShape '" + name + "' with " + shapes.size() + " shapes, total area: " + getArea(); } /** * 获取复合图形的名称 * @return 名称 */ public String getName() { return name; } /** * 设置复合图形的名称 * @param name 新的名称 */ public void setName(String name) { this.name = name; } /** * 设置颜色 * @param color 新的颜色 */ public void setColor(String color) { this.color = color; } /** * 获取子图形的数量 * @return 子图形数量 */ public int getShapeCount() { return shapes.size(); } }