使用建造者模式创建一个流式API
2020-12-17 00:08
标签:demo 就是 package span test 很多 简单 lin class 说明: 2.如果一类有很多属性,可以写成链式调用,这样可以减少客户端的setXX操作,提供代码可读性。 使用建造者模式创建一个流式API 标签:demo 就是 package span test 很多 简单 lin class 原文地址:https://www.cnblogs.com/zengpinlin/p/14118007.html使用建造者模式创建一个流式API
package com.zengpinlin.aopdemo.model;
public class User {
private String userName;
private String age;
private String password;
/**
* 私有构造参数
*
* @param build
*/
private User(Build build) {
age = build.age;
password = build.password;
userName = build.userName;
}
public static void main(String[] args) {
User user = new Build()
.age("test")
.password("test")
.userName("test")
.build();
System.out.println("user = " + user);
}
@Override
public String toString() {
return "User{"
+ "userName=‘"
+ userName
+ ‘\‘‘
+ ", age=‘"
+ age
+ ‘\‘‘
+ ", password=‘"
+ password
+ ‘\‘‘
+ ‘}‘;
}
public static class Build {
private String userName;
private String age;
private String password;
public Build() {}
public Build(String userName, String age, String password) {
this.age = age;
this.userName = userName;
this.password = password;
}
public Build userName(String userName) {
this.userName = userName;
return this;
}
public Build age(String age) {
this.age = age;
return this;
}
public Build password(String password) {
this.password = password;
return this;
}
public User build() {
return new User(this);
}
}
}