Java 建筑模式
建筑模式(Builder Pattern)是一种创建型设计模式,它允许在不暴露对象创建逻辑的情况下创建复杂的对象。
以下是一个基本的建筑模式的示例,用Java语言实现:
public class House {
private String walls;
private String doors;
private String windows;
private String roof;
public House(String walls, String doors, String windows, String roof) {
this.walls = walls;
this.doors = doors;
this.windows = windows;
this.roof = roof;
}
public String getWalls() {
return walls;
}
public String getDoors() {
return doors;
}
public String getWindows() {
return windows;
}
public String getRoof() {
return roof;
}
public static class Builder {
private String walls;
private String doors;
private String windows;
private String roof;
public Builder() {}
public Builder walls(String walls) {
this.walls = walls;
return this;
}
public Builder doors(String doors) {
this.doors = doors;
return this;
}
public Builder windows(String windows) {
this.windows = windows;
return this;
}
public Builder roof(String roof) {
this.roof = roof;
return this;
}
public House build() {
return new House(walls, doors, windows, roof);
}
}
}
在这个示例中,我们有一个House类,它有四个属性:墙、门、窗和屋顶。它还有一个名为Builder的内部静态类,用于构建House对象。Builder类有四个可选方法,用于设置House对象的四个属性。最后,它有一个build()方法,用于创建House对象。
使用建筑模式的主要好处是可以轻松地创建具有多个属性的对象,而不需要编写冗长的构造函数或使用大量的setter方法。此外,它还可以帮助避免对象创建时的错误或不一致。
以上就是Java建筑模式的一个基本示例。