- 找商家买电脑:
public class Computer {
private String brand;
private String screan;
private String mainboard;
private String memory;
// getter and setter
@Override
public String toString() {
return "Computer [brand=" + brand + ", screan=" + screan + ", mainboard=" + mainboard + ", memory=" + memory
+ "]";
}
}
只需告诉他,你要 lenove 的电脑,他会帮你搞定。商家从厂商拿货,你从商家拿货:
class BuyComputer {
public static void main(String[] args) {
Director seller = new Director(new LenovoBuilder());
Computer computer = seller.build();
System.out.println(computer);
}
}
所有厂商都是对电脑组装:
public abstract class ComputerBuilder {
abstract void buildBrand();
abstract void buildScrean();
abstract void buildMainboard();
abstract void buildMemory();
abstract Computer build();
}
其中 lenovo 的厂商这样制造:
public class LenovoBuilder extends ComputerBuilder {
private Computer computer = new Computer();
@Override
public Computer build() {
return this.computer;
}
@Override
public void buildBrand() {
this.computer.setBrand("lenovo");
}
@Override
public void buildScrean() {
this.computer.setScrean("lenovo screan");
}
@Override
public void buildMainboard() {
this.computer.setMainboard("lenovo mainboard");
}
@Override
public void buildMemory() {
this.computer.setMemory("lenovo memory");
}
}
商家具体做的事情就是联系厂商,及组装什么配件:
public class Director {
private ComputerBuilder builder;
public Director(ComputerBuilder builder) {
this.builder = builder;
}
public Computer build() {
this.builder.buildBrand();
this.builder.buildScrean();
this.builder.buildMainboard();
this.builder.buildMemory();
return this.builder.build();
}
}
- 自己从 JD 买电脑配件:
public static void main(String[] args) {
JD jd = new Computer.JD();
Computer computer = jd.setBrand("lenovo").setMainboard("lenovo mainboard")
.setMemory("suming memory").setScrean("aiguo screan")
.build();
System.out.println(computer);
}
具体实现:
public class Computer {
private String brand;
private String screan;
private String mainboard;
private String memory;
private Computer() {}; // 对外屏蔽,对内开放
private Computer(JD jd) {
this.brand = jd.brand;
this.screan = jd.screan;
this.mainboard = jd.mainboard;
this.memory = jd.memory;
}
public static final class JD {
private String brand;
private String screan;
private String mainboard;
private String memory;
public Computer build() {
return new Computer(this);
}
public JD setBrand(String brand) {
this.brand = brand;
return this;
}
public JD setScrean(String screan) {
this.screan = screan;
return this;
}
public JD setMainboard(String mainboard) {
this.mainboard = mainboard;
return this;
}
public JD setMemory(String memory) {
this.memory = memory;
return this;
}
}
@Override
public String toString() {
return "Computer [brand=" + brand + ", screan=" + screan + ", mainboard=" + mainboard + ", memory=" + memory
+ "]";
}
}