语雀原文
1、概述
- 用来构造一个复杂的对象
- .Builder开启set各种属性,提供链式调用,最终.create()输出构造的对象
2、代码
public class Computer {
private String CPU;
private String GPU;
private int memorySize;
private Computer(Builder builder) {
CPU = builder.CPU;
GPU = builder.GPU;
memorySize = builder.memorySize;
}
public static class Builder{
private String CPU = "inter-i3";
private String GPU = "GTX-960";
private int memorySize = 8;
public Builder setCPU(String CPU){
this.CPU = CPU;
return this;
}
public Builder setGPU(String GPU){
this.GPU = GPU;
return this;
}
public Builder setMemorySize(int memorySize) {
this.memorySize = memorySize;
return this;
}
public Computer create(){
return new Computer(this);
}
}
}
public class Test {
public static void main(String args[]){
Computer computer = new Computer.Builder()
.setCPU("mycpu")
.setGPU("mygpu")
.setMemorySize(16)
.create();
}
}