使用java按照工厂设计模式写出案例并画出类图
时间: 2023-05-25 09:04:36 浏览: 118
以下是一个简单的工厂设计模式案例,该案例是一个汽车工厂,可以从工厂中生产不同类型的汽车:
Car.java:
```java
public abstract class Car {
private String name;
public Car(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract void assemble();
}
```
Ford.java:
```java
public class Ford extends Car {
public Ford(String name) {
super(name);
}
public void assemble() {
System.out.println("Assembling " + getName() + " by Ford");
}
}
```
Chevrolet.java:
```java
public class Chevrolet extends Car {
public Chevrolet(String name) {
super(name);
}
public void assemble() {
System.out.println("Assembling " + getName() + " by Chevrolet");
}
}
```
CarFactory.java:
```java
public class CarFactory {
public Car createCar(String type, String name) {
Car car = null;
if (type.equals("Ford")) {
car = new Ford(name);
} else if (type.equals("Chevrolet")) {
car = new Chevrolet(name);
}
return car;
}
}
```
使用例子:
```java
public class Main {
public static void main(String[] args) {
CarFactory carFactory = new CarFactory();
Car ford = carFactory.createCar("Ford", "Mustang");
Car chevrolet = carFactory.createCar("Chevrolet", "Camaro");
ford.assemble();
chevrolet.assemble();
}
}
```
类图如下:
![Factory Design Pattern UML Class Diagram](https://i.imgur.com/6iuuU7V.png)
阅读全文