话不多说直接上代码
一.Java 实现
public class User {
private String name;
private String age;
public static builder(){
return new Builder();
}
public static class Builder{
private User user;
public Builder name(String name){
user.name = name;
return this;
}
public Builder age(int age){
user.age = age;
return this;
}
public User build(){
return user;
}
}
public String toString(){
return "name: " + name + "age" + age;
}
public static void main(String [] args){
User user = User.builder().name("aaa").age(1);
Sysout.out.print(user);
}
/** ... get set 方法省略 */
}
二. JavaScript
function User(){
var _this = this;
this.setAge= function (age){
_this.age = age
return _this ;
}
this.setName= function(name){
_this.name = name;
return _this;
}
}
var user = new User();
user.setAge(1).setName("测试");
总结
核心思想是方法调用时直接返回当前对象!