建造者模式(Builder Pattern)是一种创建型设计模式,它允许通过分步骤来构建复杂对象。该模式的核心原理是将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表现形式。
在建造者模式中,通常有以下角色:
// 抽象产品类
public abstract class Computer {
protected String motherboard;
protected String cpu;
protected String memory;
// 其他属性和方法...
public abstract void buildMotherboard(String motherboard);
public abstract void buildCpu(String cpu);
public abstract void buildMemory(String memory);
public abstract Computer getComputer();
}
// 具体产品类
public class DesktopComputer extends Computer {
@Override
public void buildMotherboard(String motherboard) {
this.motherboard = motherboard;
}
@Override
public void buildCpu(String cpu) {
this.cpu = cpu;
}
@Override
public void buildMemory(String memory) {
this.memory = memory;
}
@Override
public Computer getComputer() {
return this;
}
}
// 抽象建造者类
public abstract class ComputerBuilder {
protected Computer computer;
public ComputerBuilder() {
computer = new DesktopComputer(); // 或其他实现类
}
public abstract void buildMotherboard();
public abstract void buildCpu();
public abstract void buildMemory();
public Computer getComputer() {
return computer;
}
}
// 具体建造者类
public class HighEndDesktopBuilder extends ComputerBuilder {
@Override
public void buildMotherboard() {
computer.buildMotherboard("High End Motherboard");
}
@Override
public void buildCpu() {
computer.buildCpu("Intel Core i9");
}
@Override
public void buildMemory() {
computer.buildMemory("64GB RAM");
}
}
// 导演者类(可选)
public class Director {
private ComputerBuilder builder;
public Director(ComputerBuilder builder) {
this.builder = builder;
}
public Computer constructComputer() {
builder.buildMotherboard();
builder.buildCpu();
builder.buildMemory();
return builder.getComputer();
}
}
// 使用示例
public class Client {
public static void main(String[] args) {
ComputerBuilder builder = new HighEndDesktopBuilder();
Director director = new Director(builder);
Computer highEndPC = director.constructComputer();
System.out.println(highEndPC);
}
}
想象你正在经营一家电脑装配店,客户可以选择定制自己的台式机。抽象建造者就像是一个装配说明书,列出了装机的所有步骤;具体建造者则按照说明书中每一步骤去实际安装主板、CPU和内存等配件;而导演者则是根据客户的订单要求,指挥建造者按正确的顺序进行装配。最后得到的就是一台完全符合客户需求的定制化台式电脑。