建造者模式
当你需要创建一个可能有许多配置选项的对象时, 该模式会特别有用
图解
示例
定义接口
public interface Builder {
void setType(Type type);
void setSeats(int seats);
}
接口实现类
public class CarBuilder implements Builder {
private Type type;
private int seats;
@Override
public void setType(Type type) {
this.type = type;
}
@Override
public void setSeats(int seats) {
this.seats = seats;
}
//这里是core
public Car build() {
return new Car(type, seats);
}
}
汽车类
public class Car {
private final Type type;
private final int seats;
public Car(Type type, int seats) {
this.type = type;
this.seats = seats;
}
public Type getType() {
return type;
}
public int getSeats() {
return seats;
}
@Override
public String toString() {
return "Car{" +
"type=" + type +
", seats=" + seats +
'}';
}
}
枚举
public enum Type {
CITY_CAR, SPORTS_CAR, SUV
}
测试
public class Demo {
public static void main(String[] args) {
CarBuilder builder = new CarBuilder();
//不断设置属性
builder.setSeats(1);
builder.setType(Type.SUV);
//最后build生成对象
System.out.println(builder.build().toString());
}
}
注解
@Builder 注解