用java编写一个建造器模式
时间: 2023-04-03 09:04:18 浏览: 93
建造器模式是一种创建型设计模式,它允许你创建不同风格的对象,同时避免构造函数污染。在Java中,你可以使用以下代码实现建造器模式:
public class Person {
private final String name;
private final int age;
private final String address;
private final String phone;
public static class Builder {
private String name;
private int age;
private String address;
private String phone;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public Builder setAddress(String address) {
this.address = address;
return this;
}
public Builder setPhone(String phone) {
this.phone = phone;
return this;
}
public Person build() {
return new Person(this);
}
}
private Person(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.address = builder.address;
this.phone = builder.phone;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
public String getPhone() {
return phone;
}
}
在这个例子中,我们创建了一个Person类,它有四个属性:name、age、address和phone。我们使用Builder类来构建Person对象,Builder类有四个setter方法,用于设置Person对象的属性。最后,我们在build()方法中创建Person对象,并将Builder对象传递给Person的构造函数。这种方法可以避免构造函数的参数过多,同时也可以让代码更加清晰易懂。
阅读全文