Java构建器
构建复杂对象的方式。
静态工厂和构造器都不能很好的构建大量的可选参数,当一个类创建时需要多个参数且不是所有参数都必须时,有以下解决方案:
一惯采用充重叠构造器模式——在这种模式下,你提供第一个只有必要参数的构造器,第二个构造器有一个可选参数,第三个有两个可选参数,依次类推。
- 缺点: 当有许多参数时,客户端的代码难写且难以阅读。
通过JavaBeans模式
创建无参的构造器,通过setter方案来对属性进行赋值
//People类 public class People{ private int higher; private int weighter; ... public setHiger(int higher){ this.higher = higher; } .... }
//People类包含人的基本属性 先创建无参people对象
People people = new People();
//属性赋值
people.setHiger("178");
prople.setweighter("54");
- 缺点:构造过程分到几个调用中,在构造过程中JavaBean可能处于不一致的状态。类无法仅仅通过检验构造器参数的有效性来保证一致性。
Bulider模式
一个构建QQ邮箱bean实例
package com.netty.mail;
/**
* Created by Forgot on 2017/7/8.
*/
public class MailMessage {
private String topic;
private String content;
private String qq_email;
//是否发送附件 默认不发送
private boolean flag = false;
//文件位置
private String filepath;
public String getFilepath() {
return filepath;
}
public void setFilepath(String filepath) {
this.filepath = filepath;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public String getQq_email() {
return qq_email;
}
public void setQq_email(String qq_email) {
this.qq_email = qq_email;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public static class Bulider {
private String topic;
private String content;
private boolean flag = false;
private String qq_email;
private String filepath;
public Bulider topic(String val) {
topic = val;
return this;
}
public Bulider content(String val) {
content = val;
return this;
}
public Bulider qq_email(String val) {
qq_email = val;
return this;
}
public Bulider flag(boolean val){
flag = val;
return this;
}
public Bulider filepath(String val){
filepath = val;
return this;
}
public MailMessage build(){
return new MailMessage(this);
}
}
private MailMessage(Bulider bulider){
topic = bulider.topic;
content = bulider.content;
qq_email = bulider.qq_email;
flag = bulider.flag;
filepath = bulider.filepath;
}
}