有一类实体是形状(Shape)包含矩形(Rectangle)、圆形(Circle)等,请使用工厂方法模式(FactoryMethod)实现该要求。 1.画出类结构图 2.采用java语言实现该工厂方法模式,并写测试程序main()进行测试
时间: 2024-01-05 09:03:12 浏览: 61
以下是类结构图:
```
+------ ShapeFactory ------+
| |
| |
| createShape(shapeType) |
| |
+---------------+-----------+
|
|
------------------------------------------------------
| | |
| | |
+-------- Rectangle -------+ +------- Circle --------+ +------- Triangle --------+
| | | | | |
| -length: double | | -radius: double | | -base: double |
| -width: double | | | | -height: double |
| | | | | |
| +Rectangle(length, | | +Circle(radius) | | +Triangle(base, height) |
| width) | | | | |
| +getArea(): double | | +getArea(): double | | +getArea(): double |
| | | | | |
+-------------------------- +------------------------ +----------------------------+
```
以下是使用 Java 实现的代码:
```java
// Shape.java
public interface Shape {
double getArea();
}
// Rectangle.java
public class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double getArea() {
return length * width;
}
}
// Circle.java
public class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
// Triangle.java
public class Triangle implements Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double getArea() {
return 0.5 * base * height;
}
}
// ShapeFactory.java
public class ShapeFactory {
public Shape createShape(String shapeType) {
if (shapeType.equals("Rectangle")) {
return new Rectangle(5.0, 3.0);
} else if (shapeType.equals("Circle")) {
return new Circle(4.0);
} else if (shapeType.equals("Triangle")) {
return new Triangle(5.0, 3.0);
} else {
return null;
}
}
}
// Main.java
public class Main {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape rectangle = shapeFactory.createShape("Rectangle");
System.out.println("Rectangle area: " + rectangle.getArea());
Shape circle = shapeFactory.createShape("Circle");
System.out.println("Circle area: " + circle.getArea());
Shape triangle = shapeFactory.createShape("Triangle");
System.out.println("Triangle area: " + triangle.getArea());
}
}
```
运行 `Main.java` 后,输出如下:
```
Rectangle area: 15.0
Circle area: 50.26548245743669
Triangle area: 7.5
```
阅读全文
相关推荐















