step-builder 建造者模式
- step-builder 建造者模式是链式建造者模式的近一步扩展, 能够按步骤实例化对象.
- 还是以建造一个Compute为例,代码如下↓↓↓
public class Computer {
private String cpu;
private String ram;
private String screen;
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public String getRam() {
return ram;
}
public void setRam(String ram) {
this.ram = ram;
}
public String getScreen() {
return screen;
}
public void setScreen(String screen) {
this.screen = screen;
}
}
public class ComputerBuilder {
private ComputerBuilder() {}
public static CpuStep getBuilder(){
return new ComputerSteps();
}
interface CpuStep{
RamStep withCpu(String cpu);
}
interface RamStep{
ScreenStep withRam(String ram);
}
interface ScreenStep{
BuildStep withScreen(String screen);
}
interface BuildStep{
Computer build();
}
public static class ComputerSteps implements CpuStep,RamStep,ScreenStep,BuildStep{
private Computer computer;
public ComputerSteps() {
this.computer = new Computer();
}
@Override
public RamStep withCpu(String cpu) {
this.computer.setCpu(cpu);
return this;
}
@Override
public ScreenStep withRam(String ram) {
this.computer.setRam(ram);
return this;
}
@Override
public BuildStep withScreen(String screen) {
this.computer.setScreen(screen);
return this;
}
@Override
public Computer build() {
return this.computer;
}
}
}
public static void main(String[] args) {
Computer computer = ComputerBuilder.getBuilder().withCpu("cpu型号").withRam("ram型号").withScreen("屏幕型号").build();
}
- 将每一步抽象为一个接口, 完成第一步后返回的是下一步的接口,以此保证只能按照接口顺序执行.