需求: 对于复杂的对象,我们只需要 通过 设置一些参数,就可以得到相对应的 实例。
简单来说, 需求就是用一个类 通过方法返回一个 新建的对象,而且可以通过方法去设置这个对象
public interface CarBuilder {
void setCarName(String name);
void setCarModel(String model);
Car getCar();
}
这个类有一个 内部私有 car, 通过getCar ,输出 car的实例。
package com.example.builder;
public class CarBuilderImp implements CarBuilder {
private Car car = new Car ();
@Override
public void setCarName( String name) {
car.setName(name);
}
@Override
public void setCarModel(String model) {
car.setModel( model);
}
@Override
public Car getCar() {
return car;
}
}
package com.example.builder;
import android.util.Log;
import androidx.annotation.NonNull;
public class Car {
String name;
String model;
public void setName(String name) {
this.name = name;
}
public void setModel(String model) {
this.model = model;
}
public String getName() {
return name;
}
public String getModel() {
return model;
}
@NonNull
@Override
public String toString() {
Log.d("Car"+"LIU","name = " + this.name + "model = " + this.model);
return this.name + this.model;
}
}
example
CarBuilderImp carBuilderImp = new CarBuilderImp();
carBuilderImp.setCarModel("X1");
carBuilderImp.setCarName("BMW");
Car car = carBuilderImp.getCar();
2024-10-05 11:53:36.966 18346-18346/com.example.builder D/CarLIU: name = BMWmodel = X1
参考:百度安全验证
https://github.com/youlookwhat/DesignPattern#11-%E5%BB%BA%E9%80%A0%E8%80%85%E6%A8%A1%E5%BC%8F