例子:
public interface CPU {
}
class IntelCPU implements CPU{
}
class AMDCPU implements CPU{
}
public interface Memory {
}
class KingstonMemory implements Memory{
}
class SamsungMemory implements Memory{
}
public interface Mainboard {
}
class AsusMainboard implements Mainboard{
}
class GaMainboard implements Mainboard{
}
public class Computer {
private CPU cpu;
private Memory memory;
private Mainboard mainboard;
get/set
}
public interface ComputerBuilder {
public void buildCPU();
public void buildMemory();
public void buildMainboard();
public Computer getComputer();
}
public class LenoveComputerBuilder implements ComputerBuilder {
private Computer lenoveComputer;
public LenoveComputerBuilder(){
lenoveComputer = new Computer();
}
public void buildCPU() {
lenoveComputer.setCpu(new IntelCPU());
}
public void buildMemory() {
lenoveComputer.setMemory(new KingstonMemory());
}
public void buildMainboard() {
lenoveComputer.setMainboard(new AsusMainboard());
}
public Computer getComputer() {
return lenoveComputer;
}
}
public class HPComputerBuilder implements ComputerBuilder {
private Computer HPComputer;
public HPComputerBuilder(){
HPComputer = new Computer();
}
public void buildCPU() {
HPComputer.setCpu(new AMDCPU());
}
public void buildMemory() {
HPComputer.setMemory(new SamsungMemory());
}
public void buildMainboard() {
HPComputer.setMainboard(new GaMainboard());
}
public Computer getComputer() {
return HPComputer;
}
}
public class Director {
private ComputerBuilder builder;
public Director(ComputerBuilder builder) {
this.builder = builder;
}
public void construct() {
builder.buildCPU();
builder.buildMemory();
builder.buildMainboard();
}
}
public class Test {
public static void main(String[] args) {
Computer lenoveComputer = null;
ComputerBuilder lenoveComputerBuilder = new LenoveComputerBuilder();
Director director = new Director(lenoveComputerBuilder);
director.construct();
lenoveComputer = lenoveComputerBuilder.getComputer();
System.out.println(lenoveComputer);
}
}