请给出一个建造者模式的实例
时间: 2024-05-10 20:15:56 浏览: 120
假设我们要构建一个汽车对象,有许多属性,如品牌,型号,颜色,发动机类型等。以下是建造者模式的实现:
首先,我们创建一个汽车对象:
```
public class Car {
private String brand;
private String model;
private String color;
private String engineType;
public Car(String brand, String model, String color, String engineType) {
this.brand = brand;
this.model = model;
this.color = color;
this.engineType = engineType;
}
}
```
然后,我们创建一个汽车构建器类,负责设置汽车对象的各个属性:
```
public class CarBuilder {
private String brand;
private String model;
private String color;
private String engineType;
public CarBuilder setBrand(String brand) {
this.brand = brand;
return this;
}
public CarBuilder setModel(String model) {
this.model = model;
return this;
}
public CarBuilder setColor(String color) {
this.color = color;
return this;
}
public CarBuilder setEngineType(String engineType) {
this.engineType = engineType;
return this;
}
public Car build() {
return new Car(brand, model, color, engineType);
}
}
```
最后,我们使用汽车构建器类来构建汽车对象:
```
Car car = new CarBuilder()
.setBrand("Toyota")
.setModel("Camry")
.setColor("Red")
.setEngineType("Gasoline")
.build();
```
通过使用建造者模式,我们可以将复杂对象的构建过程和表示分离,使得代码更加简洁和易于维护。
阅读全文