漫谈设计模式之:Builder模式
程序员文章站
2022-06-04 17:01:49
...
概述
Builder模式主要用于解决初始化类时(也就是new一个类的实例出来),类的构造函数种类过多,且不易管理的问题。
我们看一下有三个参数的类,能构建出多少个构造函数:
public class Student {
private String name;
private int age;
private boolean sex;
public Student() {
}
public Student(String name) {
this.name = name;
}
public Student(int age) {
this.age = age;
}
public Student(boolean sex) {
this.sex = sex;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student(String name, boolean sex) {
this.name = name;
this.sex = sex;
}
public Student(int age, boolean sex) {
this.age = age;
this.sex = sex;
}
public Student(String name, int age, boolean sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public Student(StudentBuilder studentBuilder) {
this.name = studentBuilder.name;
this.age = studentBuilder.age;
this.sex = studentBuilder.sex;
}
}
一共有9种!
如果这些构造函数都写到类里面,不仅代码量大,代码不美观,而且调用起来容易搞错。
解决方案
我们的想法是Student类的构造函数不要那么多,但是又要满足初始化Student类变量的需求。
我们可以设计一个内部类,这个内部类的参数跟Student类参数一样,而Student类的构造函数的参数,我们就设定为这个内部类。所以我们只需要将这个内部类的变量初始化完即可。
内部类变量设定的时候,我们采用链式结构,这样可以通过setxx().setxx.()这样的形式一直写下去。
目前RxJava、OkHttp等框架均采取了这样的链式结构设计。
代码
public class Student {
private String name;
private int age;
private boolean sex;
public Student(StudentBuilder studentBuilder) {
this.name = studentBuilder.name;
this.age = studentBuilder.age;
this.sex = studentBuilder.sex;
}
public static StudentBuilder newInstance() {
return new StudentBuilder();
}
public static class StudentBuilder {
private String name;
private int age;
private boolean sex;
public StudentBuilder setName(String name) {
this.name = name;
return this;
}
public StudentBuilder setAge(int age) {
this.age = age;
return this;
}
public StudentBuilder setSex(boolean sex) {
this.sex = sex;
return this;
}
public Student build() {
return new Student(this);
}
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", sex=" + sex +
'}';
}
}
调用:
Student student1 = new Student.StudentBuilder().setName("张三").setAge(18).setSex(true).build();
mTextView1.setText(student1.toString());
Student student2 = Student.newInstance().setName("李四").setAge(20).setSex(false).build();
mTextView2.setText(student2.toString());
git地址
上一篇: 一言不合就闪退?