建造者模式
建造者模式(Builder Pattern)允许你逐步构建复杂的对象。这种模式将对象的构造过程与其表示分离,使得相同的构造过程可以创建不同的表示。建造者模式特别适用于需要创建具有多个部件或复杂配置的对象时。
使用建造者模式构造对象并完成链式调用:
需要创建的对象:
java
@Data
@ToString
public class Phone {
String cpu;
String mem;
String disk;
String camera;
}
抽象建造者类及其实现子类:
java
public abstract class AbstractPhoneBuilder {
Phone phone;
public abstract AbstractPhoneBuilder customCpu(String cpu);
public abstract AbstractPhoneBuilder customMem(String mem);
public abstract AbstractPhoneBuilder customDisk(String disk);
public abstract AbstractPhoneBuilder customCamera(String camera);
public Phone getPhone(){
return this.phone;
}
}
java
public class PhoneBuilder extends AbstractPhoneBuilder{
public PhoneBuilder() {
this.phone = new Phone();
}
@Override
public AbstractPhoneBuilder customCpu(String cpu) {
phone.setCpu(cpu);
return this;
}
@Override
public AbstractPhoneBuilder customMem(String mem) {
phone.setMem(mem);
return this;
}
@Override
public AbstractPhoneBuilder customDisk(String disk) {
phone.setDisk(disk);
return this;
}
@Override
public AbstractPhoneBuilder customCamera(String camera) {
phone.setCamera(camera);
return this;
}
}
测试:
java
public class Main {
public static void main(String[] args) {
PhoneBuilder builder = new PhoneBuilder();
Phone phone = builder.customCpu("晓龙999")
.customMem("32g")
.customDisk("1tb")
.customCamera("1亿")
.getPhone();
System.out.println(phone);
}
}