package com;
final class Computer {
final String CPU;
final String RAM;
@Override
public String toString() {
return "Computer{" +
"CPU='" + CPU + '\'' +
", RAM='" + RAM + '\'' +
'}';
}
public Computer(Builder builder) {
this.CPU = builder.CPU;
this.RAM = builder.RAM;
}
public Builder newBuilder(){
return new Builder(this);
}
public static final class Builder {
String CPU;
String RAM;
public Builder() {
this.CPU = "intel";
this.RAM = "kingston";
}
public Builder(Computer computer){
this.CPU = computer.CPU;
this.RAM = computer.RAM;
}
public Builder CPU(String CPU) {
this.CPU = CPU;
return this;
}
public Builder RAM(String RAM) {
this.RAM = RAM;
return this;
}
public Computer build() {
return new Computer(this);
}
}
}
public class App2 {
public static void main(String[] args) {
Computer computer = new Computer.Builder().CPU("amd").build();
System.out.println(computer);
Computer computer2 = computer.newBuilder().RAM("kelvv").build();
System.out.println(computer2);
}
}
参考:
https://segmentfault.com/a/1190000017497699