简化建造模式的Java代码
时间: 2023-07-03 08:07:40 浏览: 73
JAVA设计模式之简单粗暴学建造者模式.docx
简化建造模式(Fluent Builder Pattern)是建造模式的一种变体,它主要用于创建复杂对象并提供一种更加简洁的语法。以下是一个简化建造模式的Java代码示例:
```java
public class Car {
private String make;
private String model;
private int year;
private int mileage;
public Car(String make, String model, int year, int mileage) {
this.make = make;
this.model = model;
this.year = year;
this.mileage = mileage;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
public int getMileage() {
return mileage;
}
public static class Builder {
private String make;
private String model;
private int year;
private int mileage;
public Builder make(String make) {
this.make = make;
return this;
}
public Builder model(String model) {
this.model = model;
return this;
}
public Builder year(int year) {
this.year = year;
return this;
}
public Builder mileage(int mileage) {
this.mileage = mileage;
return this;
}
public Car build() {
return new Car(make, model, year, mileage);
}
}
}
```
使用简化建造模式创建对象的示例代码:
```java
Car car = new Car.Builder()
.make("Honda")
.model("Civic")
.year(2020)
.mileage(1000)
.build();
```
通过使用链式调用的方式,可以更加方便地创建对象,同时也避免了过多的构造函数重载。
阅读全文