有一类实体是形状(Shape)包含矩形(Rectangle)、圆形(Circle)等,请使用工厂方法模式(FactoryMethod)实现该要求。 1.画出类结构图 2.采用java语言实现该工厂方法模式,并写测试程序main()进行测试
时间: 2024-01-04 18:03:37 浏览: 77
c++ 形状类Shape(派生出圆类Circle和矩形类Rectangle)
这是类结构图:
```
+--------------+ +------------+
| Shape | | ShapeFactory |
+--------------+ +------------+
| draw() |<-------| createShape |
+--------------+ +------------+
/|\
|
+------------+-----+------------+
| |
+------------+ +------------+
| Rectangle | | Circle |
+------------+ +------------+
```
这是Java代码实现:
首先是Shape接口:
```java
public interface Shape {
void draw();
}
```
然后是Rectangle类:
```java
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing rectangle");
}
}
```
接着是Circle类:
```java
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing circle");
}
}
```
现在是ShapeFactory类:
```java
public class ShapeFactory {
public Shape createShape(String type) {
if (type.equalsIgnoreCase("Rectangle")) {
return new Rectangle();
} else if (type.equalsIgnoreCase("Circle")) {
return new Circle();
} else {
return null;
}
}
}
```
最后是测试程序main():
```java
public class FactoryMethodTest {
public static void main(String[] args) {
ShapeFactory factory = new ShapeFactory();
Shape shape1 = factory.createShape("Rectangle");
shape1.draw();
Shape shape2 = factory.createShape("Circle");
shape2.draw();
}
}
```
输出结果:
```
Drawing rectangle
Drawing circle
```
阅读全文