1、什么是建造者模式
使用多个简单的对象构建成一个复杂的对象
2、建造者模式实操
- 场景:需要创建一个Person对象,有name、age、sex属性,获取其中任意的属性赋值后,创建Person对象
- 创建Person类
public class Person {
private String name;
private int age;
private boolean sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
// 构建器,静态内部类
public static class Builder{
private String name;
private int age;
private boolean sex;
public Builder name(String name){
name = name;
return this;
}
public Builder age(int age){
age = age;
return this;
}
public Builder sex(boolean sex){
sex = sex;
return this;
}
public Person build(){
return new Person(this);
}
}
private Person(Builder builder){
name = builder.name;
age = builder.age;
sex = builder.sex;
}
}
- 测试调用类
public class Test {
public static void main(String[] args) {
// 内部静态类的调用 new 主类名.静态类名();
Person p = new Person.Builder().name("mars").age(21).sex(true).build();
System.out.println(p.getName() + " ," + p.getAge() + " ," + p.isSex());
}
}
3、总结
- 构建者模式有利有弊,遇到多个构造器参数时要考虑用建造者模式构建
- 书籍参考:《Effective Java》第二条目
网友评论