设计模式之建造者模式
设计模式 Java 大约 1310 字作用
用原型实例指定创建对象的种类,并且通过拷贝这些原型来创建新的对象。
案例
通过User.Builder类构建User。
User user = User.builder().name("张三").age(20).city("SH").build();
class User {
private String name;
private int age;
private String city;
public User(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
public static User.Builder builder() {
return new Builder();
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", city='" + city + '\'' +
'}';
}
static class Builder {
private String name;
private int age;
private String city;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Builder city(String city) {
this.city = city;
return this;
}
public User build() {
return new User(this.name, this.age, this.city);
}
}
}
源码
java.lang.AbstractStringBuilder#append(java.lang.String)
AbstractStringBuilder是抽象类不能实例化,所以使用StringBuilder来充当Builder角色。
阅读 1431 · 发布于 2019-12-16
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Windows 后台启动 Nginx、Redis、MongoDB、php-fpm阅读 2771
-
Linux 查看内存信息阅读 2420
-
Nginx 配置静态文件 404(root 与 alias 区别)阅读 5063
-
Spring 循环依赖能否用二级缓存解决阅读 2092
-
Vue 透传 Attribute阅读 344
-
npm Hostname/IP does not match certificate's altnames阅读 2554
-
Docker 配置容器的数据卷阅读 861
-
Python 基础语法阅读 1624
-
软考-系统架构设计师:NoSQL阅读 1950
-
Vue $refs 操作 DOM 元素阅读 373