介绍
建造者模式(Builder Pattern)属于创建型模式。当一个复杂的对象由很多部分组成,构建者模式将它拆分基本部分和可组合部分,将变与不变分离开。就像是饺子,碗、饺子皮是不变的,而馅,料汁等等是会改变的。
优点
- 建造者独立,易扩展
- 便于处理细节
缺点
- 必须有基本部分
- 可组合部分多的话,也比较复杂
应用
不相同部分装配到对象影响结果时,内部实现复杂时,框架的初始化等等,例如图片缓存框架加载,okhttp、retrofit的初始化,stringbuilder
实现
关键代码
建造者:创建和提供实例
director:管理建造出来的实例的依赖关系
代码1:builder
// 创建接口
interface Builder {
void setCarType(CarType type);
void setSeats(int seats);
void setWheels(int wheels);
}
// 实现建造者类
class CarBuilder implements Builder {
private CarType type;
private int seats;
private int wheels;
// private int price;
@Override
public void setCarType(CarType type) {
this.type = type;
}
@Override
public void setSeats(int seats) {
this.seats = seats;
}
@Override
public void setWheels(int wheels) {
this.wheels= wheels;
}
Car getCar(){
return new Car(type, seats, wheels);
}
}
// 实现实体类
class Car {
private final CarType carType;
private final int seats;
private final int wheels;
private final boolean manned;
public Car(CarType carType, int seats, int wheels) {
this.carType = carType;
this.seats = seats;
this.wheels = wheels;
this.manned = true;
}
public CarType getCarType() {
return carType;
}
public int getSeats() {
return seats;
}
public int getWheels() {
// this.wheels = wheels;
return wheels;
}
public void read(){
System.out.println("carType:"+carType);
System.out.println("seats:"+seats);
System.out.println("wheels:"+wheels);
System.out.println("manned:"+manned);
}
}
// 枚举车的类型
enum CarType {
CITY_CAR, SPORTS_CAR, BIKE
}
// 进行组合创建
class Director{
public void cityCar(Builder builder){
builder.setCarType(CarType.CITY_CAR);
builder.setSeats(4);
builder.setWheels(4);
}
public void bike(Builder builder){
builder.setCarType(CarType.BIKE);
builder.setSeats(2);
builder.setWheels(2);
}
}
class Demo {
public static void main(String[] args) {
Director director = new Director();
CarBuilder cb = new CarBuilder();
director.cityCar(cb);
Car car = cb.getCar();
car.read();
}
}
运行结果:
carType:CITY_CAR
seats:4
wheels:4
manned:true
代码2:连点调用
class Car {
private CarType carType;
private int seats;
private int wheels;
private boolean manned = true;
public static class Builder{
Car car;
public Builder() {
this.car = new Car();
}
public <T> Builder Cartype(T t) {
this.car.carType = (CarType)t;
return this;
}
public Builder Seats(int seats) {
this.car.seats= seats;
return this;
}
public Builder Wheels(int wheels) {
this.car.wheels = wheels;
return this;
}
public Car build() {
return car;
}
}
public void product(){
System.out.println("carType:"+carType);
System.out.println("seats:"+seats);
System.out.println("wheels:"+wheels);
System.out.println("manned:"+manned);
}
}
enum CarType {
CITY_CAR, SPORTS_CAR, BIKE
}
class Demo{
public static void main(String[] args) {
Car car = new Car.Builder()
.Cartype(CarType.CITY_CAR)
.Wheels(4)
.Seats(4)
.build();
car.product();
}
}
运行结果:
carType:CITY_CAR
seats:4
wheels:4
manned:true