链式编程,也叫级联式编程,调用对象的函数时返回一个this对象指向对象本身,达到链式效果,可以级联调用。
链式编程: 通过高阶函数以点为连接将多个函数连接在一起完成参数传递和复杂的操作!通俗的说是通过点号(.)链接在一起成为一句代码。
链式编程的优点是:编程性强、可读性强、代码简洁。
举例:
StringBuilder builder = new StringBuilder(96);
builder.append("select id, name from ")
.append(T_USER)
.append(" where id = ")
.append(userId)
.append(";");
简单举例:
public class User {
private Integer id;
private String userName;
private String password;
private String nikeName;
private String email;
private String phoneNum;
public Integer getId() {
return id;
}
public User setId(Integer id) {
this.id = id;
return this;
}
public String getUserName() {
return userName;
}
public User setUserName(String userName) {
this.userName = userName;
return this;
}
public String getPassword() {
return password;
}
public String getNikeName() {
return nikeName;
}
public User setNikeName(String nikeName) {
this.nikeName = nikeName;
return this;
}
public String getEmail() {
return email;
}
public User setEmail(String email) {
this.email = email;
return this;
}
public String getPhoneNum() {
return phoneNum;
}
public User setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
return this;
}
public User setPassword(String password) {
this.password = password;
return this;
}
}
调用:
User user = new User();
user.setId(1).setUserName("name").setPhoneNum("pNo").setNikeName("NikeName").setEmail("xxxxx").setPassword("122");
经典模式
package builder;
/**
* Builder模式,链式调用Demo<br>
*
* @author junehappylove
*
*/
public class User {
private final String firstName;
private final String lastName;
private final int age;
private final String phone;
private final String address;
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return address;
}
//Builder
public static class UserBuilder {
private final String firstName;
private final String lastName;
private int age;
private String phone;
private String address;
public UserBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}
public UserBuilder address(String address) {
this.address = address;
return this;
}
public User build() {
// 由于Builder是非线程安全的,所以如果要在Builder内部类中检查一个参数的合法性,
// 必需要在对象创建完成之后再检查
User user = new User(this);
if (user.getAge() < 0 || user.getAge() > 255) {
throw new IllegalStateException("Age out of range:" + user.getAge());// 线程安全
}
return user;
}
}
public static void main(String[] args) {
User june = new User.UserBuilder("Wang", "wei").age(18).address("qdao").build()