我需要你使用简单工厂模式设计一个可以创建不同集合状态的绘图工具类,要求会支不支持的几何图形时抛出一个UnsupportedShapeException异常,绘制类图并使用Java语言变成模拟实现
时间: 2023-06-05 22:04:22 浏览: 96
好的,我会尽力满足你的要求。以下是该绘图工具类的设计:
1.创建不同集合状态的接口 Shape
```java
public interface Shape {
void draw();
}
```
2. 创建各种几何图形类实现 Shape 接口
```java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("绘制圆形");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("绘制正方形");
}
}
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("绘制矩形");
}
}
```
3. 创建简单工厂类,根据不同的参数创建不同的对象
```java
public class ShapeFactory {
public static Shape getShape(String shapeType) throws UnsupportedShapeException {
if (shapeType == null) {
throw new UnsupportedShapeException("不支持的几何图形");
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
}
throw new UnsupportedShapeException("不支持的几何图形");
}
}
```
4. 创建测试类进行测试
```java
public class Test {
public static void main(String[] args) {
try {
Shape circle = ShapeFactory.getShape("CIRCLE");
circle.draw();
Shape square = ShapeFactory.getShape("SQUARE");
square.draw();
Shape rectangle = ShapeFactory.getShape("RECTANGLE");
rectangle.draw();
Shape shape = ShapeFactory.getShape("TRIANGLE"); // 不支持的几何图形
shape.draw();
} catch (UnsupportedShapeException e) {
System.out.println(e.getMessage());
}
}
}
```
类图如下:
![image](https://user-images.githubusercontent.com/57208256/114247329-b8404a00-99aa-11eb-837f-3c3fc3b88fc1.png)
以上就是使用简单工厂模式设计一个可以创建不同集合状态的绘图工具类的过程。希望能满足你的需求。