Builder模式在java中是使用非常频繁的一种设计模式,依赖静态内部类的形式存在于实体对象中,该内部类用于生成所在实体对象。
如下是一个学生实体类
public class Student {
private String name;
private int age;
private char sex;
public Student(String name, int age, char sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
/**
* 静态内部类,用于生成一个Student对象
*/
private static class Builder{
private Student target;
public Builder name(String name){
target.name = name;
return this;
}
public Builder age(int age){
target.age = age;
return this;
}
public Builder sex(char sex){
target.sex = sex;
return this;
}
public Student build(){
return target;
}
}
}
通常采用
Student s1 = new Student("小明", 18, '男');
的方式例化Student对象,优点是简单,但是同时也带来先天的劣势,当参数过多,代码变长,鬼知道每个参数代表的什么意思,并且此种方式参数的顺序是固定的。
于是乎,Builder模式孕育而生,它解决了传统实例化对象带来的开发、维护中可读性不强的问题。那么它是如何实例化对象的呢?
Student s2 = new Student.Builder()
.age(18)
.name("八戒")
.sex('男')
.build();