将部件和其组装过程分开,一步一步创建一个复杂的对象,并且对于客户端而言不需要知道具体构建细节
// 复杂对象电脑
public class Computer {
private Mouse mouse;
private Keyboard keyboard;
private CPU cpu;
public Mouse getMouse() {
return mouse;
}
public void setMouse(Mouse mouse) {
this.mouse = mouse;
}
public Keyboard getKeyboard() {
return keyboard;
}
public void setKeyboard(Keyboard keyboard) {
this.keyboard = keyboard;
}
public CPU getCpu() {
return cpu;
}
public void setCpu(CPU cpu) {
this.cpu = cpu;
}
public void display() {
System.out.println("cpu:" + this.cpu.getName() + " mouse:" + this.mouse.getName()
+ " keyboard:" + this.keyboard.getName());
}
}
// 部件鼠标
public class Mouse {
private String name;
public Mouse(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// 部件键盘
public class Keyboard {
private String name;
public Keyboard(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// 部件处理器
public class CPU {
private String name;
public CPU(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public interface ComputerBuilder {
Mouse buildMouse();
Keyboard buildKeyboard();
CPU buildCPU();
}
public class DellComputerBuilder implements ComputerBuilder {
@Override
public Mouse buildMouse() {
return new Mouse("dell brand mouse");
}
@Override
public Keyboard buildKeyboard() {
return new Keyboard("dell brand keyboard");
}
@Override
public CPU buildCPU() {
return new CPU("dell brand cpu");
}
}
public interface ComputerDirector {
Computer directComputer();
}
public class DellComputerDirector implements ComputerDirector {
private ComputerBuilder builder;
public DellComputerDirector(ComputerBuilder builder) {
this.builder = builder;
}
@Override
public Computer directComputer() {
Mouse mouse = builder.buildMouse();
Keyboard keyboard = builder.buildKeyboard();
CPU cpu = builder.buildCPU();
Computer computer = new Computer();
computer.setMouse(mouse);
computer.setKeyboard(keyboard);
computer.setCpu(cpu);
return computer;
}
}
public class ComputerBuilderTest {
public static void main(String[] args) {
ComputerDirector director = new DellComputerDirector(new DellComputerBuilder());
Computer computer = director.directComputer();
computer.display();
}
}