您的位置:首页 > 产品设计 > UI/UE

多构造器下考虑选用Builder

2016-07-14 15:49 211 查看
多参数,多构造器下考虑。

易读

线程安全

简单例子

package com.wj.test.cases.model;

import java.sql.Timestamp;
import java.util.Date;

/**
* Created by wangjia on 16/3/24 22:15
*/
public class User {
private final String name;
private final int age;
private final Date birthday;
private final Timestamp createTime;
private final Timestamp updateTime;

private User(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.createTime = builder.createTime;
this.birthday = builder.birthday;
this.updateTime = builder.updateTime;
}

public static class Builder {
private final String name;
private int age;
private Timestamp createTime;
private Date birthday;
private Timestamp updateTime;

//required
public Builder(String name) {
this.name = name;
}

public Builder age(int age) {
this.age = age;
return this;
}

public Builder createTime(Timestamp createTime) {
this.createTime = createTime;
return this;
}

public Builder birthday(Date birthday) {
this.birthday = birthday;
return this;
}

public Builder updateTime(Timestamp updateTime) {
this.updateTime = updateTime;
return this;
}

public User build() {
return new User(this);
}
}

@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", createTime=" + createTime +
", birthday=" + birthday +
", updateTime=" + updateTime +
'}';
}

public static void main(String[] args) {
User heiheihei = new Builder("heiheihei").age(12).birthday(new Date()).build();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息