建造者模式之项目运用
【摘要】 1 问题
建造者模式,我们也许不陌生,因为我们看到很多开源框架或者Android源码里面用到,类似这样的代码结构
A a = new A.builder().method1("111").method2("222").build();
很明显,一般这里的结构有builder()构造函数,还有build()函数,主要用来干嘛呢?还不是为了构建对象,如果需要设置的参数很多的...
1 问题
建造者模式,我们也许不陌生,因为我们看到很多开源框架或者Android源码里面用到,类似这样的代码结构
A a = new A.builder().method1("111").method2("222").build();
很明显,一般这里的结构有builder()构造函数,还有build()函数,主要用来干嘛呢?还不是为了构建对象,如果需要设置的参数很多的话,一个一个去set很繁琐也不好看,下面有个例子简单粗暴展示。
2 测试代码实现
-
package com.example.test1;
-
-
public class Student {
-
private int id;
-
private String name;
-
private int age;
-
private String classNmae;
-
-
public Student(Builder builder) {
-
this.id = builder.id;
-
this.name = builder.name;
-
this.age = builder.age;
-
this.classNmae = builder.classNmae;
-
}
-
public int getId() {
-
return id;
-
}
-
-
public String getName() {
-
return name;
-
}
-
-
public int getAge() {
-
return age;
-
}
-
-
public String getClassNmae() {
-
return classNmae;
-
}
-
-
@Override
-
public String toString() {
-
return "Student{" +
-
"id=" + id +
-
", name='" + name + '\'' +
-
", age=" + age +
-
", classNmae='" + classNmae + '\'' +
-
'}';
-
}
-
-
public static class Builder {
-
private int id;
-
private String name;
-
private int age;
-
private String classNmae;
-
-
public Builder() {}
-
public Builder id(int id) {
-
this.id = id;
-
return this;
-
}
-
public Builder name(String name) {
-
this.name = name;
-
return this;
-
}
-
public Builder age(int age) {
-
this.age = age;
-
return this;
-
}
-
public Builder className(String classNmae) {
-
this.classNmae = classNmae;
-
return this;
-
}
-
public Student build() {
-
return new Student(this);
-
}
-
}
-
}
-
Student student = new Student.Builder()
-
.name("chenyu")
-
.age(28)
-
.id(1)
-
.className("erzhong")
-
.build();
-
Log.i(TAG, "student toString is:" + student.toString());
3 运行结果
18376-18376/com.example.test1 I/chenyu: student toString is:Student{id=1, name='chenyu', age=28, classNmae='erzhong'}
4 总结
1)我们需要构建一个对象很多参数的时候用这种方式
2)最关键的是需要构建的对象类里面有个Builder类作为参数传递
-
public Student(Builder builder) {
-
this.id = builder.id;
-
this.name = builder.name;
-
this.age = builder.age;
-
this.classNmae = builder.classNmae;
-
}
3)最后build()函数里面返回的是需要构建的类本身
-
public Student build() {
-
return new Student(this);
-
}
文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。
原文链接:chenyu.blog.csdn.net/article/details/105058815
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)